hibernate

Hibernate CRUD Operations Tutorial

A CRUD operation deals with creating, retrieving, updating, and deleting records from the table. In this tutorial we will see how it is done using Hibernate annotations. We are going to discuss 4 main functionalities:

  • Creating a Record
  • Displaying Records
  • Updating a Record
  • Deleting a Record

 
 
 

1. Introduction

1.1 Hibernate

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is Java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling
  • Framework provides option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML based configuration
  • Framework handles the application interaction with the database, leaving the developer free to concentrate more on business logic and solving complex problems

Fig. 1: Hibernate Overview
Fig. 1: Hibernate Overview

1.1.1 Hibernate Annotations

  • Hibernate annotations is the newest way to define mappings without a use of an XML file
  • Developers use annotations to provide metadata configuration along with the Java code. Thus, making the code is easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than 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 defaults to column names

1.1.2 Reference Guide on Hibernate Annotations

Hibernate Annotations are based on the JPA 2 specification. All the JPA annotations are defined in the javax.persistence.* package. The basic JPA annotations of Hibernate that can be used in an entity are the ones below.

AnnotationModifierDescription
@EntityMarks a class as a Hibernate Entity (Mapped class)
@TableNameMaps this class with a database table specified by name modifier. If the name is not supplied it maps the class with a table having the same name as the class.
@IdMarks this class field as a primary key column.
@GeneratedValueInstructs database to generate a value for this field automatically.
@ColumnNameMaps this field with table column specified by name and uses the field name if name modifier is absent.

1.2 CRUD

CRUD means the basic operations to be done in a data repository. We directly handle records or data objects; apart from these operations, the records are passive entities. CRUD stands for Create, Read, Update, and Delete. The CRUD functions are the user interfaces to databases, as they permit users to create, view, modify and alter data. CRUD works on entities in databases and manipulates these entities.

For instance, a simple student database table adds (creates) new student details, accesses (reads) existing student details, modifies (updates) existing student data such as subjects, and deletes student details when students leave the school.

The commands corresponding to these operations in SQL are INSERT, SELECT, UPDATE, and DELETE. INSERT adds new records, SELECT retrieves or selects existing records based on selection conditions, UPDATE modifies existing records and DELETE removes tables or records in a table.

Fig. 2: CRUD (Create, Read, Update, Delete) Overview
Fig. 2: CRUD (Create, Read, Update, Delete) Overview

1.2.1 CRUD Benefits

Using the database operations in your applications it has some advantages i.e.

  • Improves data security and data access to users by using host and query languages
  • Greater data integrity and independence of applications programs
  • Improves application performance by reducing the data redundancy

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’s see how to implement the CRUD operations in Hibernate using Annotations!

2. Hibernate CRUD Operations Tutorial

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’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Hibernate CRUD Operations Application Project Structure
Fig. 3: Hibernate CRUD Operations Application Project Structure

2.3 Project Creation

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

Fig. 4: Create Maven Project
Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select 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 next button to proceed.

Fig. 5: Project Details
Fig. 5: 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.

Fig. 6: Archetype Parameters
Fig. 6: 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>HibernateCrud</groupId>
	<artifactId>HibernateCrud</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

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

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called tutorialDb with table: student. Open MySQL terminal or workbench terminal and execute the script:

CREATE DATABASE IF NOT EXISTS tutorialDb;

USE tutorialDb;

DROP TABLE IF EXISTS student;

CREATE TABLE IF NOT EXISTS student (
  student_id int(100) NOT NULL AUTO_INCREMENT,
  student_name varchar(50) DEFAULT NULL,
  roll_number varchar(50) DEFAULT NULL,
  course varchar(50) DEFAULT NULL,  
  PRIMARY KEY (student_id)
);

If everything goes well, the database and the table will be shown in the MySQL workbench.

Fig. 7: Database & Table Creation
Fig. 7: Database & Table Creation

3.2 Maven Dependencies

Here, we specify three dependencies for Hibernate Core, MySQL Connector and, Log4j. The rest dependencies will be automatically resolved by Maven, such as Hibernate JPA and Hibernate Commons Annotations. 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>HibernateCrud</groupId>
	<artifactId>HibernateCrud</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<dependencies>
		<!-- Hibernate 4.3.6 Final -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.6.Final</version>
		</dependency>
		<!-- Mysql Connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>
		<!-- Log4j 1.2.16 Final -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.3 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation
Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.hibernate.crud.operations.

Fig. 9: Java Package Name (com.jcg.hibernate.crud.operations)
Fig. 9: Java Package Name (com.jcg.hibernate.crud.operations)

Once the package is created in the application, we will need to create the Model, Database Operations and, Implementation classes. Right click on the newly created package: New -> Class.

Fig. 10: Java Class Creation
Fig. 10: Java Class Creation

A new pop window will open and enter the file name as Student. The POJO model class will be created inside the package: com.jcg.hibernate.crud.operations.

Fig. 11: Java Class (Student.java)
Fig. 11: Java Class (Student.java)

Repeat the step (i.e. Fig. 10) and enter the filename as DbOperations. This class will be used to perform the database operations and is created inside the package: com.jcg.hibernate.crud.operations.

Fig. 12: Java Class (DbOperations.java)
Fig. 12: Java Class (DbOperations.java)

Again, repeat the step listed in Fig. 10 and enter the file name as AppMain. The implementation class will be created inside the package: com.jcg.hibernate.crud.operations.

Fig. 13: Java Class (AppMain.java)
Fig. 13: Java Class (AppMain.java)

3.3.1 Implementation of Model Class

Add the following code to it:

Student.java

package com.jcg.hibernate.crud.operations;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

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

	private static final long serialVersionUID = 1L;

	@Id
	@Column(name="student_id")
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;

	@Column(name="student_name")
	private String studentName;

	@Column(name="roll_number")
	private int rollNumber;

	@Column(name="course")
	private String course;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public int getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getCourse() {
		return course;
	}

	public void setCourse(String course) {
		this.course = course;
	}

	@Override
	public String toString() {
		return "Student Details?= Id: " + this.id + ", Name: " + this.studentName + ", Roll No.: " + this.rollNumber + ", Course: " + this.course;
	}
}

3.3.2 Implementation of DAO Class

This class has methods that interact with the database for performing the CRUD operation on the records. Add the following code to it:

DbOperations.java

package com.jcg.hibernate.crud.operations;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class DbOperations {

	static Session sessionObj;
	static SessionFactory sessionFactoryObj;

	public final static Logger logger = Logger.getLogger(DbOperations.class);

	// This Method Is Used To Create The Hibernate's SessionFactory Object
	private static SessionFactory buildSessionFactory() {
		// Creating Configuration Instance & Passing Hibernate Configuration File
		Configuration configObj = new Configuration();
		configObj.configure("hibernate.cfg.xml");

		// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
		ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); 

		// Creating Hibernate SessionFactory Instance
		sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
		return sessionFactoryObj;
	}

	// Method 1: This Method Used To Create A New Student Record In The Database Table
	public static void createRecord() {
		int count = 0;
		Student studentObj = null;
		try {
			// Getting Session Object From SessionFactory
			sessionObj = buildSessionFactory().openSession();
			// Getting Transaction Object From Session Object
			sessionObj.beginTransaction();

			// Creating Transaction Entities
			for(int j = 101; j <= 105; j++) {
				count = count + 1;
				studentObj = new Student();				
				studentObj.setRollNumber(j);
				studentObj.setStudentName("Editor " + j);
				studentObj.setCourse("Bachelor Of Technology");	
				sessionObj.save(studentObj);
			}

			// Committing The Transactions To The Database
			sessionObj.getTransaction().commit();
			logger.info("\nSuccessfully Created '" + count + "' Records In The Database!\n");
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				logger.info("\n.......Transaction Is Being Rolled Back.......\n");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}

	// Method 2: This Method Is Used To Display The Records From The Database Table
	@SuppressWarnings("unchecked")
	public static List displayRecords() {
		List studentsList = new ArrayList();		
		try {
			// Getting Session Object From SessionFactory
			sessionObj = buildSessionFactory().openSession();
			// Getting Transaction Object From Session Object
			sessionObj.beginTransaction();

			studentsList = sessionObj.createQuery("FROM Student").list();
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				logger.info("\n.......Transaction Is Being Rolled Back.......\n");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
		return studentsList;
	}

	// Method 3: This Method Is Used To Update A Record In The Database Table	
	public static void updateRecord(int student_id) {		
		try {
			// Getting Session Object From SessionFactory
			sessionObj = buildSessionFactory().openSession();
			// Getting Transaction Object From Session Object
			sessionObj.beginTransaction();

			// Creating Transaction Entity
			Student stuObj = (Student) sessionObj.get(Student.class, student_id);
			stuObj.setStudentName("Java Code Geek");
			stuObj.setCourse("Masters Of Technology");

			// Committing The Transactions To The Database
			sessionObj.getTransaction().commit();
			logger.info("\nStudent With Id?= " + student_id + " Is Successfully Updated In The Database!\n");
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				logger.info("\n.......Transaction Is Being Rolled Back.......\n");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}

	// Method 4(a): This Method Is Used To Delete A Particular Record From The Database Table
	public static void deleteRecord(Integer student_id) {
		try {
			// Getting Session Object From SessionFactory
			sessionObj = buildSessionFactory().openSession();
			// Getting Transaction Object From Session Object
			sessionObj.beginTransaction();

			Student studObj = findRecordById(student_id);
			sessionObj.delete(studObj);

			// Committing The Transactions To The Database
			sessionObj.getTransaction().commit();
			logger.info("\nStudent With Id?= " + student_id + " Is Successfully Deleted From The Database!\n");
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				logger.info("\n.......Transaction Is Being Rolled Back.......\n");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}

	// Method 4(b): This Method To Find Particular Record In The Database Table
	public static Student findRecordById(Integer find_student_id) {
		Student findStudentObj = null;
		try {
			// Getting Session Object From SessionFactory
			sessionObj = buildSessionFactory().openSession();
			// Getting Transaction Object From Session Object
			sessionObj.beginTransaction();

			findStudentObj = (Student) sessionObj.load(Student.class, find_student_id);
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				logger.info("\n.......Transaction Is Being Rolled Back.......\n");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} 
		return findStudentObj;
	}

	// Method 5: This Method Is Used To Delete All Records From The Database Table
	public static void deleteAllRecords() {
		try {
			// Getting Session Object From SessionFactory
			sessionObj = buildSessionFactory().openSession();
			// Getting Transaction Object From Session Object
			sessionObj.beginTransaction();

			Query queryObj = sessionObj.createQuery("DELETE FROM Student");
			queryObj.executeUpdate();

			// Committing The Transactions To The Database
			sessionObj.getTransaction().commit();
			logger.info("\nSuccessfully Deleted All Records From The Database Table!\n");
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				logger.info("\n.......Transaction Is Being Rolled Back.......\n");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}
}

3.3.3 Implementation of Utility Class

This class helps in creating the SessionFactory from the Hibernate configuration file and interacts with the DAO class to perform the CRUD operations. Add the following code to it:

AppMain.java

package com.jcg.hibernate.crud.operations;

import java.util.List;

import org.apache.log4j.Logger;

public class AppMain {

	public final static Logger logger = Logger.getLogger(AppMain.class);

	public static void main(String[] args) {
		logger.info(".......Hibernate Crud Operations Example.......\n");

		logger.info("\n=======CREATE RECORDS=======\n");
		DbOperations.createRecord();

		logger.info("\n=======READ RECORDS=======\n");
		ListviewStudents = DbOperations.displayRecords();
		if(viewStudents != null & viewStudents.size() > 0) {
			for(Student studentObj : viewStudents) {
				logger.info(studentObj.toString());
			}
		}

		logger.info("\n=======UPDATE RECORDS=======\n");
		int updateId = 1;
		DbOperations.updateRecord(updateId);
		logger.info("\n=======READ RECORDS AFTER UPDATION=======\n");
		List updateStudent = DbOperations.displayRecords();
		if(updateStudent != null & updateStudent.size() > 0) {
			for(Student studentObj : updateStudent) {
				logger.info(studentObj.toString());
			}
		}

		logger.info("\n=======DELETE RECORD=======\n");
		int deleteId = 5;
		DbOperations.deleteRecord(deleteId);
		logger.info("\n=======READ RECORDS AFTER DELETION=======\n");
		List deleteStudentRecord = DbOperations.displayRecords();
		for(Student studentObj : deleteStudentRecord) {
			logger.info(studentObj.toString());
		}

		logger.info("\n=======DELETE ALL RECORDS=======\n");
		DbOperations.deleteAllRecords();
		logger.info("\n=======READ RECORDS AFTER ALL RECORDS DELETION=======");
		List deleteAll = DbOperations.displayRecords();
		if(deleteAll.size() == 0) {
			logger.info("\nNo Records Are Present In The Database Table!\n");
		}		
		System.exit(0);
	} 
}

3.4 Hibernate Configuration File

To configure the Hibernate framework, we need to implement a configuration file i.e. hiberncate.cfg.xml. Right-click on src/main/resources folder, New -> Other.

Fig. 14: XML File Creation
Fig. 14: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 15: Wizard Selection
Fig. 15: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as HibernateCrud/src/main/resources and enter the file name as hibernate.cfg.xml. Click Finish.

Fig. 16: hibernate.cfg.xml
Fig. 16: hibernate.cfg.xml

Once the file is created, we will include the database configuration and mapping classes details. Add the following code to it:

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>
		<!-- SQL Dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Database Connection Settings -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<property name="show_sql">true</property>

		<!-- Specifying Session Context -->
		<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>

		<!-- Mapping With Model Class Containing Annotations -->
		<mapping class="com.jcg.hibernate.crud.operations.Student" />
	</session-factory>
</hibernate-configuration>

Notes:

  • Here, we instructed Hibernate to connect to a MySQL database named tutorialDb and the Mapping classes to be loaded
  • We have also instructed Hibernate framework to use MySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a Hibernate SessionFactory object

4. Run the Application

To run the Hibernate application, Right click on the AppMain class -> Run As -> Java Application.

Fig. 17: Run Application
Fig. 17: Run Application

5. Project Demo

Executing the AppMain class, we will save few Student’s records and then we will apply the CRUD operations on those records. Developers can debug the example and see what happens in the database after every step. Enjoy!

Create Operation

Fig. 18: Insert Operation
Fig. 18: Insert Operation

Read Operation

Fig. 19: Read Operation
Fig. 19: Read Operation

Update Operation

Fig. 20: Update Operation
Fig. 20: Update Operation

Delete Operation

Fig. 21: Delete Operation
Fig. 21: Delete Operation

That’s all for this post. Happy Learning!!

6. Conclusion

In this article, we learned how to define Hibernate persistent classes by defining the appropriate mapping and making a simple application to perform the CRUD operations on this entity. That’s all for this tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Hibernate CRUD operations.

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

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.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Zeba
Zeba
5 years ago

ListviewStudents = DbOperations.displayRecords();
if(viewStudents != null & viewStudents.size() > 0) {
for(Student studentObj : viewStudents) {
logger.info(studentObj.toString());
}
}

logger.info(“\n=======UPDATE RECORDS=======\n”);
int updateId = 1;
DbOperations.updateRecord(updateId);
logger.info(“\n=======READ RECORDS AFTER UPDATION=======\n”);
List updateStudent = DbOperations.displayRecords();
if(updateStudent != null & updateStudent.size() > 0) {
for(Student studentObj : updateStudent) {
logger.info(studentObj.toString());
}
}

logger.info(“\n=======DELETE RECORD=======\n”);
int deleteId = 5;
DbOperations.deleteRecord(deleteId);
logger.info(“\n=======READ RECORDS AFTER DELETION=======\n”);
List deleteStudentRecord = DbOperations.displayRecords();
for(Student studentObj : deleteStudentRecord) {

ERROR ::ListviewStudents cannot be resolved to a variable

Wouter
Wouter
5 years ago
Reply to  Zeba

The first word ListviewStudents is missing a space: “List viewStudents = …”

guest23
guest23
4 years ago

The main is coded completely wrong

naveen
naveen
2 years ago

I am facing this error please help me to fix

Exception in thread “main” java.lang.NullPointerException: Cannot invoke “org.hibernate.Session.getTransaction()” because “com.jcg.hibernate.crud.operations.DbOperations.sessionObj” is null
at com.jcg.hibernate.crud.operations.DbOperations.createRecord(DbOperations.java:59)
at com.jcg.hibernate.crud.operations.AppMain.main(AppMain.java:15)

Back to top button