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



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

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

杰森:

{"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.

最新更新