gpt4 book ai didi

java - 让 JPA/Hibernate 复制 "ON DELETE SET NULL"功能

转载 作者:IT老高 更新时间:2023-10-28 21:01:21 31 4
gpt4 key购买 nike

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

这是我的两个类(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<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: 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.

我做错了吗?是不是可以实现?

谢谢。

最佳答案

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

On delete set null in hibernate in @OneToMany

JBs 的解决方案看起来很干净:

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

您还应该能够将其放入 PreRemove:

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

关于java - 让 JPA/Hibernate 复制 "ON DELETE SET NULL"功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9944137/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com