Menu

Cascading and Orphan Removal

Cascading and Orphan Removal

Cascading

By default, an operation on a parent entity does not reach its related entities. Cascading passes the operation on. You set it with the cascade attribute.

Type

Passes on

PERSISTpersist()
MERGEmerge()
REMOVEremove()
REFRESHrefresh()
DETACHdetach()
ALLAll of the above

Orphan Removal

orphanRemoval = true deletes a child row when the child is removed from the parent's collection. It fits relationships where the child cannot exist without the parent, such as order lines in an order.

@OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();

department.addEmployee(employee);
session.persist(department);

department.getEmployees().remove(employee);

Code Explanation:

  • With CascadeType.ALL, persisting the department also persists the new employee.
  • Removing the employee from the list makes it an orphan, and Hibernate deletes its row at flush.
  • Deleting the department would also delete all its employees.

Use cascading only from a parent to children it owns. In Hibernate 7, the old Hibernate-specific types SAVE_UPDATE and DELETE no longer exist, so use the standard types above.


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details