I have a Department entity which relations are as follows:
Many departments can be in one parent department:
@ManyToOne
@JoinColumn(name = "ik_parent_department_id")
private Department parentDepartment;
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?
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));
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With