On delete set null in hibernate in @OneToMany

后端 未结 3 1995
南笙
南笙 2021-01-07 17:43

I have a Department entity which relations are as follows:

  1. Many departments can be in one parent department:

    
    
            
相关标签:
3条回答
  • 2021-01-07 18:24

    You'll have to set the children's ik_parent_department_id to null explicitly.

    Department parentDepartment = (Department) session.load(Department.class, id);
    session.delete(parentDepartment);
    for (Department child : parentDepartment.getChildren()){
        child.setParentDepartment(null);
    } 
    session.flush();
    

    With cascading you would only manage to delete child Departments.

    0 讨论(0)
  • 2021-01-07 18:30

    With JPA, in parent Entity you might have something like

    @OneToMany(mappedBy="parent", cascade={CascadeType.PERSIST})
    Collection<Child> children;
    

    and in order to avoid possible repeating "set null code" & integrity violation exceptions on parent removal implement in parent Entity also

    @PreRemove
    private void preRemove() {
       children.forEach( child -> child.setParent(null));
    }
    
    0 讨论(0)
  • 2021-01-07 18:35

    Just code it:

    for (Department child : parent.getChildren()) {
        child.setParentDepartment(null);
    }
    session.delete(parent);
    
    0 讨论(0)
提交回复
热议问题