hibernate

Hibernate CascadeType.REMOVE Example

Greeting readers, in this tutorial, we will create two entity classes related to each other and will perform the cascading operations between them.

1. Introduction

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides the reference implementation of Java Persistence API that makes it a great choice as an ORM tool with benefits of loose coupling
  • A Framework that an option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well as XML based configuration
Hibernate CascadeType.REMOVE - Hibernate Overview
Fig. 1: Hibernate Overview

1.1 Hibernate Annotations

  • Hibernate annotations are the newest way to define mappings without the use of a XML file
  • Developers use annotations to provide metadata configuration along with the Java code. Thus, making the code easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than the XML configuration and should only be used for table and column mappings
  • Annotations are preconfigured with sensible default values, which reduce the amount of coding required. For e.g., Class name defaults to Table name and Field names default to Column names

1.2 Cascade Types in Hibernate

Cascading is a phenomenon involving one object propagating to other objects via a relationship. It is transitive in nature and the cascade attribute in hibernate defines the relationship between the entities. The cascading types supported by the hibernate framework are as follow:

  • CascadeType.PERSIST: It means that the save() and persist() operations in the hibernate cascade to the related entities
  • CascadeType.MERGE: It means that the related entities are joined when the owning entity is joined
  • CascadeType.REMOVE: It means that the related entities are deleted when the owning entity is deleted
  • CascadeType.DETACH: It detaches all the related entities if a manual detach occurs
  • CascadeType.REFRESH: It works similar to the refresh() operation in the hibernate
  • CascadeType.ALL: It is an alternative for performing all the above cascade operations in the hibernate framework

1.3 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.4 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

Now, open up the Eclipse IDE and let us see how to implement the CascadeType.REMOVE operation in the hibernate framework!

2. Hibernate CascadeType.REMOVE Example

Here is a systematic guide for implementing this tutorial in the hibernate framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Hibernate CascadeType.REMOVE - Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Hibernate CascadeType.REMOVE - Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Hibernate CascadeType.REMOVE - Project Details
Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Hibernate CascadeType.REMOVE - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hibernate.cascade</groupId>
	<artifactId>HibernateCascadeTypeRemove</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Hibernate cascade type remove example</name>
	<packaging>jar</packaging>
</project>

We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database and Table Creation

The following script creates a database called cascadedb with tables: student and subject. Open MySQL terminal or workbench to execute this sql script.

---- DATABASE CREATION ----
create database if not exists cascadedb;

use cascadedb;

---- STUDENT TABLE CREATION ----
create table student (s_id integer not null, age integer not null, name varchar(255), subj_s_id integer, primary key (s_id));

---- SUBJECT TABLE CREATION ----
create table subject (s_id integer not null, marks integer not null, name varchar(255), primary key (s_id));

---- ADD FOREIGN KEY CONSTRAINT TO THE STUDENT TABLE ----
alter table student add constraint FK8ngu5xmekwnx1882pmvgxwak foreign key (subj_s_id) references subject (s_id);

---- INSERT DATA IN SUBJECT TABLE ----
insert into subject (s_id, marks, name) values ('101', '90', 'Science'), ('102', '100', 'Mathematics');

---- INSERT DATA IN STUDENT TABLE ----
insert into student (s_id, age, name, subj_s_id) values ('1', '24', 'Michael', '101'), ('2', '22', 'John', '102');

If everything goes well, the database and table (having dummy records) will be created as shown in Fig. 6.

Hibernate CascadeType.REMOVE - Database & Table creation
Fig. 6: Database & Table creation

3.2 Maven Dependencies

Here, we specify the dependencies for the Hibernate framework and the MySQL connector. Maven will automatically resolve the rest dependencies such as Persistence, MySQL etc. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hibernate.cascade</groupId>
	<artifactId>HibernateCascadeTypeRemove</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Hibernate cascade type remove example</name>
	<description>A tutorial to understand cascadetype.remove in the hibernate5 framework</description>
	<packaging>jar</packaging>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.4.0.CR2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.13</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.3 Java Class Creation

Let us write the Java classes involved in this application.

3.3.1 Implementation of Subject Class

This class maps the model attributes with the table column names. Add the following code to the model definition to map the attributes with the column names.

Subject.java

package com.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity  
@Table(name="subject")  
public class Subject {

	@Id  
	private int s_id;
	
	private String name;
	
	private int marks;
	
	public int getS_id() {
		return s_id;
	}
	
	public void setS_id(int s_id) {
		this.s_id = s_id;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getMarks() {
		return marks;
	}
	
	public void setMarks(int marks) {
		this.marks = marks;
	}

	@Override
	public String toString() {
		return "Subject [s_id=" + s_id + ", name=" + name + ", marks=" + marks + "]";
	}
}

3.3.2 Implementation of Student Class

This class maps the model attributes with the table column names and has an object of the Subject type for the cascade operation. Add the following code to the model definition to map the attributes with the column names.

Student.java

package com.hibernate.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity  
@Table(name="student")  
public class Student {  

	@Id  
	private int s_id;

	private String name;

	private int age;

	@OneToOne(cascade= { CascadeType.REMOVE })
	private Subject subj;

	public int getS_id() {
		return s_id;
	}
	
	public void setS_id(int s_id) {
		this.s_id = s_id;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	public Subject getSubj() {
		return subj;
	}
	
	public void setSubj(Subject subj) {
		this.subj = subj;
	}

	@Override
	public String toString() {
		return "Student [s_id=" + s_id + ", name=" + name + ", age=" + age + ", subj=" + subj + "]";
	}
}

3.3.3 Implementation of Utility Class

Add the following code to the implementation class for implementing the CascadeType.REMOVE operation in the hibernate framework.

AppMain.java

package com.hibernate.util;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

import com.hibernate.model.Student;

public class AppMain {

	public static void main(String[] args) {		
		// Creating the configuration instance & passing the hibernate configuration file.
		Configuration config = new Configuration();
		config.configure("hibernate.cfg.xml");

		// Hibernate session object to start the db transaction.
		Session s = config.buildSessionFactory().openSession();
		
		// Fetching the data from the database.
		int student_id = 1;
		Student student = s.get(Student.class, student_id);
		
		System.out.println(student.toString());
		
		// Deleting the data from the database.
		s.getTransaction().begin();
		
		s.remove(student);
		
		s.getTransaction().commit();
		
		// Closing the session object.
		s.close();
	}
} 

3.4 Hibernate Configuration File

In the configuration file, we will include the database and the mapping class details.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Database connection settings -->
		<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/cascadedb</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password" />

		<!-- Sql dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

		<!-- Printing the sql queries to the console -->
		<property name="show_sql">true</property>

		<!-- Mapping to the create schema DDL -->
		<property name="hbm2ddl.auto">validate</property>

		<!-- Model classes -->
		<mapping class="com.hibernate.model.Subject" />
		<mapping class="com.hibernate.model.Student" />
	</session-factory>
</hibernate-configuration>

Important points:

  • Here, we instructed Hibernate to connect to a MySQL database named cascadedb and the mapping class to be loaded
  • We have also instructed the Hibernate framework to use MySQL5Dialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a hibernate SessionFactory object
  • hbm2ddl.auto tag will instruct the hibernate framework to create the table schema at the application startup
  • show_sql tag will instruct the hibernate framework to log all the SQL statements on the console

4. Run the Application

To run the Hibernate application, Right-click on the AppMain class -> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Hibernate CascadeType.REMOVE - Run Application
Fig. 7: Run Application

5. Project Demo

The code shows the following images as the output of this tutorial.

Student table – The student id= 1 will be removed from the table as shown in Fig. 8.

Hibernate CascadeType.REMOVE - Updated Student Table
Fig. 8: Updated Student Table

Subject table – Due to the cascade remove property, the details related to student id= 1 will also be deleted from the subject table as shown in Fig. 9.

Fig. 9: Updated Subject Table

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the implementation of cascading operations in hibernate framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of implementing the CascadeType.REMOVE operation in hibernate framework for beginners.

Download
You can download the full source code of this example here: HibernateCascadeTypeRemove

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button