让 JPA/Hibernate 复制“ON DELETE SET NULL";功能 [英] Have JPA/Hibernate to replicate the "ON DELETE SET NULL" functionality

查看:41
本文介绍了让 JPA/Hibernate 复制“ON DELETE SET NULL";功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been able to have JPA/Hibernate to replicate the ON DELETE CASCADE functionality successfully (seems like the default behaviour) but I'm now trying to replicate the ON DELETE SET NULL functionality and I'm facing problems.

这是我的两个类:

@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;

    // ...
}

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

When I try to delete a teacher, the following error appears:

org.springframework.dao.DataIntegrityViolationException: 无法执行 JDBC 批量更新;SQL [从老师那里删除老师_id=?];约束 [null]
...
引起:org.hibernate.exception.ConstraintViolationException:无法执行JDBC批量更新
...
引起:java.sql.BatchUpdateException:从教师中删除批次条目 0,其中教师 ID =1"被中止.调用 getNextException 查看原因.

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?

谢谢.

推荐答案

目前似乎无法使用 jpa/hibernate.

It doesn't appear to be possible at the moment with jpa/hibernate.

在@OneToMany 的休眠中删除 set null

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

JBs solution seems clean though:

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆