当我尝试使用Spring Boot 2.1.6.RELEASE和Spring Data JPA将用户对象保存到数据库时遇到问题。
json:
{"name" : "Jhon",
"detail":
{
"city" : "NY"
}
}
userController.java:
...
@PostMapping(value="/user")
public Boolean agregarSolicitiud(@RequestBody User user) throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
userRepository.save(user);
...
User.java:
...
@Entity
public class User {
@Id
@Column(updatable=false, nullable=false, unique=true)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@OneToOne(mappedBy = "solicitud",optional=false,cascade=CascadeType.ALL)
private UserDetail userDetail;
}
UserDetail.java:
...
@Entity
public class UserDetail {
@Id
@Column
private Long id;
@Column
private String city;
@MapsId
@OneToOne(optional = false,cascade = CascadeType.ALL)
@JoinColumn(name = "id", nullable = false)
private User user;
}
userRepository.java
...
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
...
错误:
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [proyect.model.Detail.user]
我该怎么办?
谢谢
答案 0 :(得分:0)
通过这篇文章,我可以保存两个实体。
https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/
此代码需要添加到适当绑定用户详细信息的用户实体中
public void setUserDetail(UserDetail userDetail) {
if (userDetail == null) {
if (this.userDetail != null) {
this.userDetail.setUser(null);
}
} else {
userDetail.setUser(this);
}
this.userDetail = userDetail;
}
````
This code sets the user to the userDetails which is causing the issue.
As mentioned in the comments the deserializer is not able to bind the objects properly.The above code will binds the userDetails.user.