org.hibernate.id.IdentifierGenerationException: “attempted to assign id from null one-to-one property”

青春壹個敷衍的年華 提交于 2020-01-25 07:24:13

问题


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.

  1. user object and detail object have a bidirectional one-to-one relation.
  2. The id of detail have a foreign key to id of user(the id of user is autoincrement).
  3. user information is map from json format to a object with @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> {
}
...

Error:

 org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [proyect.model.Detail.user]

What can i do?

Thanks


回答1:


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/

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.

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.




来源:https://stackoverflow.com/questions/57116212/org-hibernate-id-identifiergenerationexception-attempted-to-assign-id-from-nul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!