让JPA / Hibernate复制“ON DELETE SET NULL”function

我已经能够让JPA / Hibernate成功复制ON DELETE CASCADEfunction(似乎是默认行为),但我现在正在尝试复制ON DELETE SET NULLfunction,我遇到了问题。

这是我的两个class级:

 @Entity @Table(name = "teacher") public class Teacher { @Id @GeneratedValue @Column(name = "id", nullable = false, length = 4) private int id; @OneToMany(mappedBy = "teacher") private List studentList; // ... } 

 @Entity @Table(name = "student") public class Student { @Id @GeneratedValue @Column(name = "id", nullable = false, length = 4) private int id; @ManyToOne(optional = true) @JoinColumn(name = "teacher_id", nullable = true) private Teacher teacher; // ... } 

当我尝试删除教师时,会出现以下错误:

org.springframework.dao.DataIntegrityViolationException:无法执行JDBC批量更新; SQL [从老师那里删除teacher_id =?]; 约束[null]

引起:org.hibernate.exception.ConstraintViolationException:无法执行JDBC批量更新

引起:java.sql.BatchUpdateException:批量输入0从教师中删除,其中teacher_id =’1’被中止。 调用getNextException以查看原因。

难道我做错了什么? 这是可以实现的吗?

谢谢。

目前用jpa / hibernate似乎不可能。

在@OneToMany中,在hibernate中删除set null

JBs解决方案似乎很干净:

 for (Department child : parent.getChildren()) { child.setParentDepartment(null); } session.delete(parent); 

你也应该能够把它放在PreRemove中:

 @PreRemove private void preRemove() { for (Student s : studentList) { s.setTeacher(null); } } 

怎么定义

 @ForeignKey(name = "fk_student_teacher", foreignKeyDefinition = " /*FOREIGN KEY in sql that sets ON DELETE SET NULL*/") 

我认为最好的灵魂是用户SQL statament for set on delete action ass follow:

 CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT fk_column FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) ON DELETE SET NULL ); 

当用户通过其他级联删除删除行时,如果使用对此已删除行的表引用,则无法使用hibernate解决方案并返回sqlexception。