4wiz4rdisneverl4te
4wiz4rdisneverl4te

Reputation: 11

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

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

Upvotes: 1

Views: 3973

Answers (1)

user06062019
user06062019

Reputation: 691

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.


Upvotes: 2

Related Questions