![](/img/trans.png)
[英]Hibernate merge org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property
[英]org.hibernate.id.IdentifierGenerationException: "attempted to assign id from null one-to-one property"
當我嘗試使用 Spring Boot 2.1.6.RELEASE 和 Spring Data JPA 將用戶對象保存到數據庫時遇到問題。
json:
{"name" : "Jhon",
"detail":
{
"city" : "NY"
}
}
用戶控制器.java:
...
@PostMapping(value="/user")
public Boolean agregarSolicitiud(@RequestBody User user) throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
userRepository.save(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;
}
用戶詳細信息.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;
}
用戶存儲庫.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]
我能做什么?
謝謝
通過關注這篇文章,我可以保存這兩個實體。
https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/
把這看作是在不使用持久化提供程序的情況下設置兩個 java 類之間的關系。這些屬性需要由開發人員手動設置,以便它可以從他想要的方向訪問關系。
需要將此代碼添加到適當綁定用戶詳細信息的用戶實體中
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.