User
和 UserSetup
实体之间存在以下一对一关系:
@Entity
class User {
@OneToOne(mappedBy = "user", optional = false, cascade = ALL)
private UserSetup setup;
public User() {
this.setup = new UserSetup(this);
}
}
和
@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;
}
}
一切正常,但是如果我将 @NotNull
添加到 User
类的 setup
字段并调用 save
在 User
存储库上它失败了:
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}'} ]
这是怎么回事?在调试器中,我看到 setup
字段已设置。或者 @NotNull
不应与 @OneToOne
一起使用,而应使用 optional
代替?
最佳答案
根据我对 Hibernate 工作原理的理解,这可能是不可能的,因为 Hibernate 必须首先保存其中一个对象,而在保存第一个对象时,第二个对象不能在数据库中引用。
你可以做的是将 @NotNull
注释放在 User
类的 setup
字段中,据我所知你可能不想要创建一个没有任何设置的 User
,级联将负责删除链接的 UserSetup
对象,以防您删除 User
。
关于java - 如果使用@NotNull,双向一对一关系将无法保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49551046/