gpt4 book ai didi

java - 如何在 Spring Boot 中正确连接表

转载 作者:搜寻专家 更新时间:2023-10-30 23:26:39 25 4
gpt4 key购买 nike

我有一个用户,该用户有费用。在费用表中,我想要费用 ID、费用的用户和费用金额。在用户表中,我需要用户 ID、他的用户名、他的当前余额以及他所支付的所有费用的列表。

我想加入这 2 个,但我不知道如何正确引用用户,因此用户表单 Expense 类始终为 null。

首先,我发送创建用户的 post 请求:

{
"username":"abcd",
"balance":"100"
}

然后我想创建一个费用,但在这里我不确定如何正确发送一个用户:

{
"username":"abcd",
"id":"1",
"balance":"100",
"amount":"20"
}

这行不通,然后我这样试了:

{
"User":{
"username":"abcd",
"id":"1",
"balance":"100"
},
"amount":"20"
}

那也没用。

这是用户类:

@Entity
@Table(name = "Users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Username is mandatory")
private String username;
private Double balance = 0.0;

@OneToMany(mappedBy = "user")
private List<Expense> expenses;
...

我从这里删除了 getter 和 setter。

这是费用类:

@Entity
@Table(name = "Expenses")
public class Expense {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

private Double amount;
...

为了省钱我用.save()来自 JpaRepository<Expense, Long>为了检索所有内容,我使用 .findAll() .

结果总是一样的:付出所有的代价得到返回

{
"id": 1,
"user": null,
"amount": 20
}

并为所有用户获取

{
"id": 1,
"username": "abcd",
"balance": 100,
"expenses": []
}

现在我不确定是我以错误的方式发送请求还是以错误的方式加入表格,或者两者兼而有之。

编辑:这里是 ExpenseController :

@RestController
public class ExpenseController {

@Autowired
IExpenseService expenseService;

@GetMapping("/expenses")
public List<Expense> findExpenses() {
return expenseService.findAll();
}

@PostMapping("/expenses")
public void createNewExpense(@RequestBody Expense expense) {
expenseService.createNewExpense(expense);
}
}

createNewUser(...)来自 ExpenseService

@Override
public void createNewExpense(Expense expense) {
repository.save(expense);
}

ExpenseRepository :

@Repository
public interface ExpenseRepository extends JpaRepository<Expense, Long> {
}

UserController :

@RestController
public class UserController {

@Autowired
IUserService userService;

@GetMapping("/users")
public List<User> findUsers() {
return userService.findAll();
}

@GetMapping("/users/{id}")
public User findUserById(@PathVariable Long id) {
return userService.findById(id);
}

@PostMapping("/users")
public ResponseEntity<Object> createUser(@RequestBody User user) {

if (userService.checkIfUsernameIsTaken(user)) {

Map<String, Object> response = new HashMap<>();
response.put("status", HttpStatus.NOT_ACCEPTABLE);
response.put("errors", "Username is already taken");
response.put("timestamp", new Date());

return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
} else {
userService.createNewUser(user);
User currentUser = userService.findById(userService.findByUsername(user.getUsername()));
Map<String, Object> response = new HashMap<>();
response.put("id", currentUser.getId());
response.put("username", currentUser.getUsername());
response.put("balance", currentUser.getBalance());
response.put("expenses", currentUser.getExpenses());
return new ResponseEntity<>(response, HttpStatus.OK);
}
}

@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}

@PutMapping("/users/{id}/{balance}")
public void updateBalance(@PathVariable Long id, @PathVariable Double balance) {
userService.updateBalance(id, balance);
}
}

User 模型的其余部分与 Expense 模型相同。

最佳答案

尝试用这个有效负载发送post请求('user'字段以小写字母开头),我认为用户对象中的'id'字段应该足够了

  { 
"user":{
"username":"abcd",
"id":"1",
"balance":"100"
},
"amount":"20"
}

编辑:您还需要将 @JsonIgnoreProperties("expenses") 添加到您的 Expense 实体中以防止 jackson 递归读取 json

@Entity
@Table(name = "Expenses")
public class Expense {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@JsonIgnoreProperties("expenses")
@ManyToOne
@JoinColumn(name = "user_id")
private User user;

private Double amount;
.....

关于java - 如何在 Spring Boot 中正确连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56378764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com