gpt4 book ai didi

java - org.hibernate.id.IdentifierGenerationException : "attempted to assign id from null one-to-one property"

转载 作者:行者123 更新时间:2023-12-02 09:40:31 28 4
gpt4 key购买 nike

当我尝试使用 Spring Boot 2.1.6.RELEASE 和 Spring Data JPA 将用户对象保存到数据库时遇到问题。

  1. 用户对象和详细信息对象具有双向一对一关系。
  2. 明细的id与用户的id有一个外键(用户的id是自增的)。
  3. 用户信息从json格式映射到带有@RequestBody的对象。

json:

{"name" : "Jhon",
"detail":
{
"city" : "NY"
}
}

userController.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;
}

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]

我能做什么?

谢谢

最佳答案

通过关注这篇文章,我能够保存这两个实体。

https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/

将此视为在不使用持久性提供程序的情况下设置两个 java 类之间的关系。这些属性需要由开发人员手动设置,以便可以从他想要的方向访问该关系。

此代码需要添加到正确绑定(bind) userdetail 的用户实体

    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.


关于java - org.hibernate.id.IdentifierGenerationException : "attempted to assign id from null one-to-one property",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57116212/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com