Types and Examples of Cascade in Hibernate

Types and Examples of Cascade in Hibernate
Techiio-author
Written by Sagar RabidasFebruary 16, 2022
8 min read
Hibernate
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Let's start the discussion with Cascade in Hibernate

Introduction:-

On every occasion the propagation takes location from one object to every other within the hibernate framework or associated technology, persistence actions are involved in it. It's far all about what patient moves should be completed and all the attributes that have to be observed while maintaining endurance. It applies to many forms of hibernating moves that are performed and it's far transitive. This means all the toddler nodes of the parent wherein the cascade is distinctive get carried out for its baby nodes too.

The cascade is described in the affiliation with the assist of the keyword cascade and it specifies all the operations that have to be cascaded to the target of the association and primarily used while series mapping. With the aid of default, there are not any operations cascaded to the affiliation. It is the handy solution provided which saves the traces of the code needed to be brought for dealing with the nation of the other aspect while doing it manually.

Types of Cascading Values and Operations Supported by Hibernate:-

Different types of cascading values and operations supported by Hibernate are given below:

  • delete / remove
  • detach / evict
  • merge
  • lock
  • persist
  • refresh
  • replicate
  • save_update / update
  • all_delete_orphan
  • delete_orphan
  • none

Examples of Cascade in Hibernate:-

Given below are the examples:

Consider the example where we maintain the data of departments and then the subjects under each department. There is a one-to-many association between departments and subjects.

Example #1: Cascade save-update

Example of adding a department and its subjects into the database.

Firstly, we will perform the task of saving both entities individually without using the cascade property of save-update.

Code: Without Cascade

Department department = new Department();
Subject subject = new Subject();
//set the department and subject  data
subject.setDepartment(department);
department.getSubjects().add(subject);
session.save(department);
session.save(subject);

Code: With Cascade

<!-- Department.hbm.xml -->
<set name="Subject" cascade="save-update" table="subject"...>
<key>
<column name="DEPARTMENT_ID" not-null="true" />
</key>
<one-to-many class="com.college.common.Subject" />
</set>
Department department = new Department();
Subject subject = new Subject();
//set the department and subject  data
subject.setDepartment(department);
department.getSubjects().add(subject);
session.save(department);

Example #2: Cascade Delete

If we need to delete the department and all the referenced subjects then we will delete both of them individually when we are not using cascading.

Code: Without using Delete Cascade

You need to loop all the ‘subject’ and delete it one by one.

Query q = session.createQuery("from Department where departmentId = :departmentId ");
q.setParameter("departmentId", "4715");
Department department = (Department)q.list().get(0);
for (Subject sdr :department.getSubjects()){
session.delete(sdr);
}
session.delete(department);

Code: With Delete Cascade

Within the above snippet, we positioned that we needed to delete every branch and situation information one after the other even though, they were related. That is in which to delete cascade functionality can come to apply. Even as we use cascade= "delete" then if we can delete branch report all of the referenced entries of the task moreover get deleted mechanically.

<!-- Department.hbm.xml -->
<set name="subject" cascade="delete" table="Student" ...>
<key>
<column name="DEPARTMENT_ID" not-null="true" />
</key>
<one-to-many class="com.college.common.Subject" />
</set>
Query q = session.createQuery("from Department where departmentId = :departmentId ");
q.setParameter("departmentId", "4715");
Department department = (Department)q.list().get(0);
session.delete(department);

Example #3: Cascade delete-orphan

We saw that we can delete the referenced facts of a specific record when we use delete cascade robotically. Now, we will see how we can delete the handiest specific baby nodes or only a few of the referenced information of the principle record with the help of cascading but before that, we can see how this may be performed without the usage of cascading.

Code: Without delete-orphan Cascade

You need to delete the ‘subject’ one by one.

Subject sdr1 = (Subject)session.get(Subject.class,
new Integer(56));
Subject sdr2 = (Subject)session.get(Subject.class,
new Integer(57));
session.delete(sdr1);
session.delete(sdr2);

Code: With delete-orphan Cascade

Now when we delete the subjects with id 56 and 57 only related to a particular department then we can do so by simply using the cascade option of delete-orphan value.

<!-- Department.hbm.xml -->
<set name="Subject" cascade="delete-orphan" table="Student" >
<key>
<column name="DEPARTMENT_ID" not-null="true" />
</key>
<one-to-many class="com.college.common.Subject" />
</set>
Subject sdr1 = (Subject)session.get(Subject.class,
new Integer(56));
Subject sdr2 = (Subject)session.get(Subject.class,
new Integer(57));
Department department = (Department)session.get(Department.class, new Integer(2));
department.getSubjects().remove(sdr1);
department.getSubjects().remove(sdr2);
session.saveOrUpdate(department);

Cascading in Hibernate:-

Cascading can be done and enabled in either way in hibernate. By using XML mapping files or by using annotations.

XML Mapping File:

We need to declare the cascade in the relationship variable in the XML mapping file of our hibernate project.

Code:

<!-- Department.hbm.xml -->
<set name="student" cascade="save-update, delete"
table="subject" ...>
<key>
<column name="DEPARTMENT_ID" not-null="true" />
</key>
<one-to-many class="com.college.common.subject" />
</set>

Annotation:

When using annotations you may make use of @cascade annotation and point out cascade type.Save_update to enable keep and update cascade or cascade type. Delete for enabling delete operation in cascading and so on. In case you need to say more than one cascade operation, you may accomplish that with the aid of specifying them in a comma-separated string.

Code:

//Department.java
@OneToMany(mappedBy = "department")
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
public Set<subject>getsubjects() {
return this.student;
}

Hibernate
Hibernate Cascade
Cascade in Hibernate
Java
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance