如何解决ManyToOne在创建Spring Boot Hiernate JPA的两个表上给出null
例如,如果具有表“ user”和“ address”,并且一个用户可以具有1到更多地址,则该关系是一对多的。当我插入数据时,我将在同一json中插入用户和地址列表。
问题是在创建与这两个相关的字段时为null。我找不到正确的方法来插入数据,因此它将创建所有这些数据,然后还填充完成一个完整关系的字段。
我有两个相互关联的表,表“ 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) {
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);
}
}
解决方法
您需要将其用于连接列(user)=> @JoinColumn(name =“ users_id”,nullable = false)
,它不是那样的,
基本上,您还有另一个用于地址的数据库表,这意味着这些地址必须保存在数据库中,以便它们可以具有标识符和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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。