让JPA / Hibernate复制“ON DELETE SET NULL”功能 [英] Have JPA/Hibernate to replicate the "ON DELETE SET NULL" functionality
问题描述
我已经能够让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)
私人列表< Student> studentList;
// ...
}
@Entity
@Table(name =student)
public class Student
{
@Id
@GeneratedValue
@Column(name =id,nullable = false,length = 4)
private int id;
@ManyToOne(可选= true)
@JoinColumn(name =teacher_id,nullable = true)
私人教师老师;
// ...
}
当我尝试要删除教师,会出现以下错误:
org.springframework.dao.DataIntegrityViolationException:无法执行JDBC批更新; SQL [从老师的teacher_id =?删除];约束[null]
...
引起:org.hibernate.exception.ConstraintViolationException:无法执行JDBC批量更新
.. 。
导致:java.sql.BatchUpdateException:批项0从teacher_id ='1'被中止的位置删除。调用getNextException来查看原因。
我做错了什么?它是可以实现的吗?
谢谢。
目前用jpa / hibernate似乎不可能。
@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;
// ...
}
When I try to delete a teacher, the following error appears:
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.
Am I doing something wrong? Is it something achievable?
Thank you.
It doesn't appear to be possible at the moment with jpa/hibernate.
On delete set null in hibernate in @OneToMany
JBs solution seems clean though:
for (Department child : parent.getChildren()) {
child.setParentDepartment(null);
}
session.delete(parent);
You should also be able to put it in a PreRemove:
@PreRemove
private void preRemove() {
for (Student s : studentList) {
s.setTeacher(null);
}
}
这篇关于让JPA / Hibernate复制“ON DELETE SET NULL”功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!