Saturday, July 2, 2011

How to delete child elements in Parent/Child relationship - JPA

Orphans are the elements removed from a child collection in a parent/child relation ship. If You expect the deletions of child records from the database with by removing child elements from the child collection or with the deletion of parent record in a parent/child relationship with javax.persistence.CascadeType.All , it will not delete the child records from the database. But simple value typed child elements like a collection of strings, will be removed with the removal of parent object or with removal of elements from the child collection. When the parent is saved, the value-typed child objects are saved as well, when the parent is deleted, the children will be deleted. 

If the child objects being entities, not value-types, those have their own life cycle, like "Items" in a "Order". For this kind of scenario, If You want to delete child records from the database with the removal of child elements from the child collection or with the deletion of parent record, you will have to use
org.hibernate.annotations.CascadeType.DELETE_ORPHAN

public class Department {

    @OneToMany(cascade = {javax.persistence.CascadeType.ALL})
    List<Location> locations;

    @OneToMany(cascade = {CascadeType.ALL})
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)   
    List<Employee> employees;
}


Since "Location" is a simple value typed objects, javax.persistence.CascadeType.ALL will perfectly work when deleting orphans. But "Employee" is not a simple value typed objects. So We have to use hibernate's @Cascade annotation with value org.hibernate.annotations.CascadeType.DELETE_ORPHAN in order to remove orphans with removal of parent.

  • It doesn't usually make sense to enable cascade on a <many-to-one> or <many-to-many> association. Cascade is often useful for <one-to-one> and <one-to-many> associations.
  • If the child object's lifespan is bounded by the lifespan of the of the parent object make it a lifecycle object by specifying cascade="all,delete-orphan"

0 comments:

Post a Comment

Share

Widgets