How to enable cascade delete/update?

One of the key features of relational database is referential integrity which is maintained by the system by taking certain actions when referential constraints are violated. So for example what happens when:

1) A row with a referenced primary key is deleted from the referenced table
2) A referenced primary key is updated in the referenced table

In order to mantain referential integrity you can specify to use cascade deletes or cascade updates in any of the two options. The cascade is supported in both XML mapping file and annotation.

Hibernate supports several different types of cascades that can be applied to many-to-one associations as well as collections. The default cascade is none. Each cascade strategy specifies the operation or operations that should be propagated to child entities. The cascade types that you are most likely to use are the following:

all: All operations are passed to child entities: save , update , and delete.
save-update : Save and update ( and UPDATE , respectively) are passed to child entities.
delete: Deletion operations are passed to child entities.
delete-orphan: All operations are passed to child entities, and objects no longer associated with the parent object are deleted.

The cascade element is added to the desired many-to-one or collection element. For example, the following configuration instructs Hibernate to delete the child Singer elements when the parent Event is deleted:

<set name="singers" cascade="delete">
      <key column="event_id"/>
      <one-to-many class="Singer"/>
</set>

Enable Cascades using Annotations

In annotation, declared the CascadeType.SAVE_UPDATE (save, update) and CascadeType.REMOVE (delete) in @Cascade annotation.

@Entity 
public class Employee { 
// ... 
@OneToOne(cascade={CascadeType.PERSIST, CascadeType.REMOVE}) 
Address address; 
@OneToMany(mappedBy="employee", 
cascade={CascadeType.PERSIST, CascadeType.REMOVE}) 
Collection<Task> tasks; 
// ... 
}

This will cascade delete:

Query q = session.createQuery("from Employee where surname = :surname ");
q.setParameter("surname", "Smith");
Employee e= (Employee)q.list().get(0);
session.delete(e);
Found the article helpful? if so please follow us on Socials