在jpa休眠表上保存数据会使联接列为空

问题描述

我有两个相互关联的表,表“ user”和“ address”:

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

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @NotNull
    @Column(unique = true)
    private String user_name;

    @Column
    private String description;

    @OnetoMany(mappedBy = "user",cascade = CascadeType.ALL,orphanRemoval = true)
    protected Set<Address> addresses= new HashSet<>();
}

在另一个表中:

@Entity
@Table(name = "address")
@Data
public class Address{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

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

    private String description;
}

我发出了发布请求,以创建具有某些地址的新用户

@PostMapping ("/user/create")
public ResponseEntity post(@RequestBody User user) {
    userService.saveNewUser(user);
     // return
}

在发帖请求中,我发送了此json:

{
 
  "user_name": "example","description": "this is a  user description","addresses": [
    {
      "description": "this is a address 1"
    },{
      "description": "this is a address 2"
    }
  ]
}

当我插入数据时,我得到“地址”表,“ user_id”为空,数据已插入,但关系不存在? 我在这里做错了什么?请帮忙!

更新:假设我在服务上有此方法saveNewUser,如何调用更新地址?

public Oject saveNewUser(User user ) {
       // 
        return jpaRepository.save(user);
    }

解决方法

您必须手动支持所有关系。 Hibernate不会为您做这件事。 因此,您需要为每个地址设置一个用户。

public Oject saveNewUser(User user ) {
   user.getAddresses().forEach(address -> address.setUser(user));
   return jpaRepository.save(user);
}