I've the following one-to-one relation between User
and UserSetup
entities:
@Entity
class User {
@OneToOne(mappedBy = "user", optional = false, cascade = ALL)
private UserSetup setup;
public User() {
this.setup = new UserSetup(this);
}
}
and
@Entity
public class UserSetup {
@OneToOne(cascade = ALL)
@JoinColumn(name = "USER_ID", nullable = false, unique = true)
private User user;
public UserSetup(User user) {
this.user = user;
}
}
It all works well, however if I add @NotNull
to setup
field in User
class and call save
on User
repository it fails with:
Caused by: javax.persistence.RollbackException: Error while committing the transaction at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:77) at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71) at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517) ... 64 more Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [User] during update time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=setup, rootBeanClass=class User, messageTemplate='{javax.validation.constraints.NotNull.message}'} ]
What's going on? In debugger I see that setup
field is set. Or maybe @NotNull
should not be used with @OneToOne
but optional
should be used instead?