【发布时间】:2018-03-29 08:11:48
【问题描述】:
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 字段并在 User 存储库上调用 save 它将失败:
原因:javax.persistence.RollbackException:提交时出错 交易在 org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:77) 在 org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71) 在 org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517) ... 64 更多原因:javax.validation.ConstraintViolationException: 期间类 [User] 的验证失败 组的更新时间 [javax.validation.groups.Default, ] 列表 违反约束:[ ConstraintViolationImpl{interpolatedMessage='不能为空', propertyPath=setup,rootBeanClass=class 用户, messageTemplate='{javax.validation.constraints.NotNull.message}'} ]
发生了什么事?在调试器中,我看到 setup 字段已设置。或者@NotNull 不应该与@OneToOne 一起使用,而应该使用optional?
【问题讨论】:
-
列是用
not null创建的吗? -
@XtremeBaumer,是的,该列具有非空约束。
-
如何为这两个实体创建
IDs? -
你使用
GenerationType.IDENTITY,而实际上它是GenerationType.SEQUENCE? -
好吧,如果生成类型错误,我怀疑hibernate能否创建一个ID。这意味着,它不能创建一个新的
UserSetup连接到User
标签: java spring hibernate jpa spring-data