java - 如果使用@NotNull,双向一对一关系将无法保存

标签 java spring hibernate jpa spring-data

UserUserSetup 实体之间存在以下一对一关系:

@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 字段并调用 saveUser 存储库上它失败了:

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/

相关文章:

javascript - 使用侧边导航创建响应式网站

基于 Java 的 SIP 端点

java - HibernateInterceptor和proxyTargetClass有什么用

java - AWS Lambda 和 S3 - 上传的 pdf 文件为空白

Java hibernate eclipse bin 目录

java - SetMaxResults() 在 Hibernate 中未按预期工作

java - JSP请求对象没有参数

java - RMI 注册表不可用错误

java.lang.ClassCastException : com. tibco.tibjms.TibjmsxSessionImp 无法转换为 javax.jms.QueueSession

java - org.hibernate.exception.GenericJDBCException : could not execute query