我已经能够让JPA / Hibernate ON DELETE CASCADE成功复制功能(似乎是默认行为),但是我现在正在尝试复制ON DELETE SET NULL功能,并且遇到了问题。
ON DELETE CASCADE
ON DELETE SET NULL
这是我的两节课:
@Entity @Table(name = "teacher") public class Teacher { @Id @GeneratedValue @Column(name = "id", nullable = false, length = 4) private int id; @OneToMany(mappedBy = "teacher") private List<Student> 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从教师中删除,教师_id =‘1’被中止。调用getNextException以查看原因。
难道我做错了什么?这是可以实现的吗?
谢谢。
目前使用jpa / hibernate似乎还不可能。
JBs解决方案似乎很干净:
for (Department child : parent.getChildren()) { child.setParentDepartment(null); } session.delete(parent);
您还应该能够将其放入PreRemove中:
@PreRemove private void preRemove() { for (Student s : studentList) { s.setTeacher(null); } }