Have JPA/Hibernate to replicate the “ON DELETE SET NULL” functionality

后端 未结 3 999
迷失自我
迷失自我 2020-12-01 05:20

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 re

相关标签:
3条回答
  • 2020-12-01 05:46

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-01 05:51

    What about defining

    @ForeignKey(name = "fk_student_teacher",
                foreignKeyDefinition = " /*FOREIGN KEY in sql that sets ON DELETE SET NULL*/")
    

    ?

    0 讨论(0)
  • 2020-12-01 06:01

    I think that the best solution is a user SQL statement for setting on delete action as follow:

    CREATE TABLE table_name
    (
      column1 datatype null/not null,
      column2 datatype null/not null,
      ...
    
      CONSTRAINT fk_column
         FOREIGN KEY (column1, column2, ... column_n)
         REFERENCES parent_table (column1, column2, ... column_n)
         ON DELETE SET NULL
    );
    

    when user deletes a row by other cascading delete where you use a table reference to this deleted row, you could not use hibernate solution and return SQL exception.

    0 讨论(0)
提交回复
热议问题