Delete with Cascade
Let’s perform Delete operation with and without cascade to understand it better
Delete with Cascade
Annotation configuration
Applicant.java
- @OneToMany(mappedBy="applicant")
- @Cascade(CascadeType.DELETE)
- private Set<Address> addresses;
@OneToMany(mappedBy="applicant") @Cascade(CascadeType.DELETE) private Set<Address> addresses;
XML configuration
applicant.hbm.xml
- <set name="addresses" table="Address"
- inverse="true" lazy="true" fetch="select" cascade="delete">
- <key>
- <column name="Applicant_Id" not-null="true" />
- </key>
- <one-to-many class="Address" />
- </set>
<set name="addresses" table="Address" inverse="true" lazy="true" fetch="select" cascade="delete"> <key> <column name="Applicant_Id" not-null="true" /> </key> <one-to-many class="Address" /> </set>
Example to Delete Applicant and Address objects
- Applicant applicant = session.get(Applicant.class, 1);
- session.delete(applicant);
Applicant applicant = session.get(Applicant.class, 1); session.delete(applicant);
Output Queries generated
delete from Address where Address_Id=? Hibernate: delete from Address where Address_Id=? Hibernate: delete from Applicant where Applicant_Id=?
We can see that delete queries for Address are also executed even though we have deleted only Applicant which means Cascade has happened from Applicant to Address.
Output in DB
Delete without Cascade
If we want to delete both Applicant and its reference Address , we need to delete them individually but first we need to delete Address and then we need to delete Applicant.
Annotation configuration
Applicant.java
- @OneToMany(mappedBy="applicant")
- private Set<Address> addresses;
@OneToMany(mappedBy="applicant") private Set<Address> addresses;
XML configuration
applicant.hbm.xml
- <set name="addresses" table="Address"
- inverse="true" lazy="true" fetch="select">
- <key>
- <column name="Applicant_Id" not-null="true" />
- </key>
- <one-to-many class="Address" />
- </set>
<set name="addresses" table="Address" inverse="true" lazy="true" fetch="select"> <key> <column name="Applicant_Id" not-null="true" /> </key> <one-to-many class="Address" /> </set>
Example to delete Applicant and Address objects
- Applicant applicantDelete = session.get(Applicant.class, 1);
- for (Address address : applicantDelete.getAddresses()) {
- session.delete(address);
- }
- session.delete(applicantDelete);
Applicant applicantDelete = session.get(Applicant.class, 1); for (Address address : applicantDelete.getAddresses()) { session.delete(address); } session.delete(applicantDelete);
Output Queries generated
delete from Address where Address_Id=? Hibernate: delete from Address where Address_Id=? Hibernate: delete from Applicant where Applicant_Id=?
We can see that delete queries for Address are executed first as we explictely called delete on Address object using the above code and then deleted Applicant object.
Output in DB