Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

java - Have JPA/Hibernate to replicate the "ON DELETE SET NULL" functionality

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.

These are my two classes:

@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: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...