[英]org.hibernate.id.IdentifierGenerationException: "attempted to assign id from null one-to-one property"
I have a problem when i try to save the user object to database using Spring Boot 2.1.6.RELEASE and Spring Data JPA.当我尝试使用 Spring Boot 2.1.6.RELEASE 和 Spring Data JPA 将用户对象保存到数据库时遇到问题。
json: json:
{"name" : "Jhon",
"detail":
{
"city" : "NY"
}
}
userController.java:用户控制器.java:
...
@PostMapping(value="/user")
public Boolean agregarSolicitiud(@RequestBody User user) throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
userRepository.save(user);
...
User.java:用户.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:用户详细信息.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用户存储库.java
...
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
...
Error:错误:
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [proyect.model.Detail.user]
What can i do?我能做什么?
Thanks谢谢
By following this post I am able to save both the entities.通过关注这篇文章,我可以保存这两个实体。
https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/ https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/
Think of this as setting a relationship between the two java classes without using the persistence provider.These properties need to be set manually by the developer so that it can access the relation from the direction he wants.把这看作是在不使用持久化提供程序的情况下设置两个 java 类之间的关系。这些属性需要由开发人员手动设置,以便它可以从他想要的方向访问关系。
This code needs to be added to the user entity which binds the userdetail appropriately需要将此代码添加到适当绑定用户详细信息的用户实体中
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.