使用JPA/Hibernate来复制"ON DELETE SET NULL"功能
使用JPA/Hibernate来复制"ON DELETE SET NULL"功能
我已经成功地使用JPA/Hibernate实现了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 ListstudentList; // ... }
@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: Could not execute JDBC batch update; SQL [delete from teacher where teacher_id=?]; constraint [null]
...
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
...
Caused by: java.sql.BatchUpdateException: Batch entry 0 delete from teacher where teacher_id='1' was aborted. Call getNextException to see the cause.
我做错了什么吗?是否有办法实现这个功能?
谢谢。