Search code examples
hibernatejpaspring-data-jpaone-to-onebidirectional

Bidirectional @OneToOne not work when persisting child without parent


I have this situation :

Parent entity:

@Entity
public class Address {

  @OneToOne( optional = false, targetEntity = User.class, fetch = FetchType.LAZY, orphanRemoval = true )
  @JoinColumn( name = "id_user", referencedColumnName = "id" )
  private User user;

}

Child entity:

@Entity
public class User {

   @OneToOne( optional = false, targetEntity = Address.class, mappedBy = "user", fetch = FetchType.LAZY, orphanRemoval = true )
   private Address address;
}

As you can see there isn't any cascade operation in both sides. But when I save a user :

userRepository.save( new User() ); 

It throws this exception :

org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : org.company.models.User.address; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : org.company.models.User.address
.............
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : org.company.models.User.address

I want to persist only the child, it should be possible since the @JoinColumn is in the parent, so I don't need to set it before saving.
Could someone clarify me this issue? Thanks a lot


Solution

  • The problem is due to the fact your relationship between User and Address is being marked as optional=false which means it cannot be null.

    So you either need to use optional=true and allow null-values or populate the Address relationship on your User before you persist it.