如何在Spring Boot中正确联接表

时间:2019-05-30 12:55:57

标签: java database maven spring-boot

我有一个用户,该用户有费用。在费用表中,我要有费用ID,进行费用的用户和费用金额。在用户表中,我需要用户ID,用户名,当前余额以及所有费用清单。

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

首先,我发送发布请求以创建用户:

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

然后我要产生费用,但是在这里我不确定如何正确发送用户:

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

这不起作用,然后我这样尝试:

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

那也不起作用。

这是User类:

@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;
    ...

我从这里删除了吸气剂和吸气剂。

这是Expense类:

@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模型相同。

1 个答案:

答案 0 :(得分:1)

尝试使用此有效负载发送发布请求(“用户”字段以小写字母开头),我认为用户对象中的“ id”字段应该足够

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

编辑:另外,您还需要向您的Expense实体添加@JsonIgnoreProperties(“ expenses”),以防止杰克逊递归读取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;
.....