Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On delete set null in hibernate in @OneToMany

I have a Department entity which relations are as follows:

  1. Many departments can be in one parent department:

    @ManyToOne
    @JoinColumn(name = "ik_parent_department_id")
    private Department parentDepartment;
    
  2. One parent department can have many departments:

    @OneToMany(mappedBy = "parentDepartment")
    private Set<Department> children = new HashSet<Department>(0);
    

And I want to implement the next: When I delete a department, then the ik_parent_department_id parameter of all children of this department is set to null. Any ideas how to do that?

like image 377
Mahmoud Saleh Avatar asked Sep 07 '25 05:09

Mahmoud Saleh


2 Answers

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));
}
like image 51
pirho Avatar answered Sep 09 '25 05:09

pirho


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.

like image 24
Xavi López Avatar answered Sep 09 '25 06:09

Xavi López