【发布时间】:2021-02-09 13:47:15
【问题描述】:
例如,如果有表“用户”和“地址”,一个用户可以有 1 到多个地址,所以关系是一对多的。当我插入数据时,我将在同一个 json 中插入用户和地址列表。
问题是在创建与这两个相关的字段时为空。我找不到插入数据的正确方法,因此它会创建所有这些数据,然后还填充完成 onetomany 关系的字段。
我有两个相互关联的表,表“用户”和“地址”:
@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) {
jpaRepository.save(user);
// return
}
在一个帖子请求中,我发送了这个 json:
{
"user_name": "example",
"description": "this is a user description",
"comments": [
{
"description": "this is a address 1"
},
{
"description": "this is a address 2"
}
]
}
当我插入数据时,我得到“地址”表,“user_id”为空,数据已插入但关系不存在? 我在这里做错了什么?请帮忙!
更新: 我想过做这样的事情,但不知道如何称呼它:
public class User{
....
public void addAddress(Address address) {
address.setUser(this);
addresses.add(address);
}
}
【问题讨论】:
标签: java spring-boot hibernate jpa spring-data-jpa