org.hibernate.id.IdentifierGenerationException:“试图从空的一对一属性分配ID”

时间:2019-07-19 16:14:13

标签: java spring-boot spring-data-jpa

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

  1. 用户对象和详细信息对象具有双向的一对一关系。
  2. 详细信息ID具有用户ID的外键(用户ID为autoincrement)。
  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);
...

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]

我该怎么办?

谢谢

1 个答案:

答案 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.