例如,如果有表"用户";以及";地址";并且一个用户可以有1到多个地址,所以这种关系是一对多的。当我插入数据时,我会在同一个json中插入用户和地址列表。
问题是,在创建时,与这两者相关的字段为空。我找不到如何插入数据的正确方法,所以它会创建所有这些数据,然后填充完成一个女性关系的字段。
我有两个相互关联的表,表";用户";以及";地址":
@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";如果为null,则插入数据,但不存在关系?我在这里做错了什么?请帮忙!
更新:我想过做这样的事情,但不知道怎么称呼它:
public class User{
....
public void addAddress(Address address) {
address.setUser(this);
addresses.add(address);
}
}
它不是那样工作的,
基本上,您有另一个地址的DB表,这意味着这些地址必须保存在数据库中,这样它们就可以有一个标识符和user_id。
我建议为地址创建另一个存储库。当您需要向用户添加地址时这样做:
@PostMapping("/user/{id}/addAddress")
public Address addAddressToUser(@RequestBody Address newAddress, @PathVariable(name="id") int userId)
{
User selectedUser = userRepo.findById(userId).orElseThrow( /* throw your exception */);
newAddress.setUser( selectedUser );
return addressRepo.save( newAddress )
}
基本上,你必须打这样的电话:
POST http://localhost:8080/user/1/addAddress
在请求正文中,Json:
{
"description" : "This is a new Address"
}
更新:根据询问者的要求,这是一种在内部有用户和地址的情况下在一次调用中执行此操作的方法。代码未编译,但逻辑清晰。
@PostMapping("/addUser)
public User addUser(@RequestBody User newUser)
{
List<Address> addresses = newUser.getAddresses(); // We take all the addresses that are in the call
newUser.setAddresses(new List<Address>()) // We empty the addresses in this User
//Now for each address that was in the call, we save it the DB add it to user
addresses.forEach( address ->
{
address = addressRepo.save(address) // saves each address in the DB
newUser.getAddresses().add(address); // add this Address to this user (SINCE NOW IT HAS AN ID IN THE DB)
});
//After everything is finished save this user to the Db with the Addresses and return it
return userRepo.save(newUser);
}
您需要将其用于联接列(user(=>JoinColumn(name="users_id",nullable=false(