【发布时间】:2017-10-02 17:44:54
【问题描述】:
我们有这样的OneToOne双向关系:
class Student:
@PrimaryKeyJoinColumn
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@Fetch(FetchMode.JOIN)
private StudentState state;
public Student() {
super();
state = new StudentState(this);
}
public StudentState getState() {
return state;
}
class StudentState:
@MapsId
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "student")
private Student student;
@Column(name = "inactive")
private Boolean isInactive = false;
public StudentState() {
}
public StudentState(Student student) {
this.student = student;
}
public boolean isInactive() {
if (isInactive == null) {
return false;
}
return isInactive;
}
public void setIsInactive(boolean isInactive) {
this.isInactive = isInactive;
}
以及我们用来创建学生的以下代码:
Transaction t = session.beginTransaction();
Student student = new Student();
session.save(student);
student.getState().setIsInactive(true);
t.commit();
代码在 Hibernate 4 中运行良好。
在 Hibernate 5 中,它与 org.hibernate.exception.ConstraintViolationException: could not execute statement 一起崩溃
错误。
启用“显示 sql”表明在事务提交上休眠尝试在 insert Student 查询之前执行 insert StudentState 查询。它导致:
Caused by: org.postgresql.util.PSQLException:
ERROR: insert or update on table "studentstate" violates foreign key constraint "fk77j3mjaigcfotxlor35mdsl56"'
Detail: Key (student)=(12) is not present in table "students".
任何想法为什么会发生,为什么它以前有效以及如何解决它? TIA
【问题讨论】:
-
您的数据库架构是否发生了变化?听起来确实是在插入而不是在提交时检查约束...
-
数据库模式是一样的。唯一改变的是 hibernate 4 库更改为 hibernate 5 以及依赖项(jpa、ehcache 等)
-
有没有办法让hibernate提前提交?
-
在hibernate中发现一个bug,导致insert语句在某些不应该切换的情况下切换
标签: java postgresql hibernate migration