On delete set null in hibernate in @OneToMany

后端 未结 3 2014
南笙
南笙 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条回答
  •  旧时难觅i
    2021-01-07 18:30

    With JPA, in parent Entity you might have something like

    @OneToMany(mappedBy="parent", cascade={CascadeType.PERSIST})
    Collection 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));
    }
    

提交回复
热议问题