hibernate

Hibernate CRUD Operations Tutorial

Photo of YatinYatinAugust 24th, 2017Last Updated: February 20th, 2019
4 2,891 10 minutes read

ACRUD 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 useannotations 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 thejavax.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 byname modifier. If thename 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 byname and uses the field name ifname 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 forCreate,Read,Update, andDelete. 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 areINSERT,SELECT,UPDATE, andDELETE.INSERT adds new records,SELECT retrieves or selects existing records based on selection conditions,UPDATE modifies existing records andDELETE 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 readthis tutorial in order to download and install Hibernate in the Eclipse IDE.

1.4 Download and Install MySQL

You can watchthis 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 toFile -> 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 default0.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 apom.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 calledtutorialDb 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. Theupdated 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 onsrc/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 asStudent. ThePOJO 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 asDbOperations. 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 asAppMain. 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;}@Overridepublic 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 Objectprivate static SessionFactory buildSessionFactory() {// Creating Configuration Instance & Passing Hibernate Configuration FileConfiguration configObj = new Configuration();configObj.configure("hibernate.cfg.xml");// Since Hibernate Version 4.x, ServiceRegistry Is Being UsedServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); // Creating Hibernate SessionFactory InstancesessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);return sessionFactoryObj;}// Method 1: This Method Used To Create A New Student Record In The Database Tablepublic static void createRecord() {int count = 0;Student studentObj = null;try {// Getting Session Object From SessionFactorysessionObj = buildSessionFactory().openSession();// Getting Transaction Object From Session ObjectsessionObj.beginTransaction();// Creating Transaction Entitiesfor(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 DatabasesessionObj.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 SessionFactorysessionObj = buildSessionFactory().openSession();// Getting Transaction Object From Session ObjectsessionObj.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 Tablepublic static void updateRecord(int student_id) {try {// Getting Session Object From SessionFactorysessionObj = buildSessionFactory().openSession();// Getting Transaction Object From Session ObjectsessionObj.beginTransaction();// Creating Transaction EntityStudent stuObj = (Student) sessionObj.get(Student.class, student_id);stuObj.setStudentName("Java Code Geek");stuObj.setCourse("Masters Of Technology");// Committing The Transactions To The DatabasesessionObj.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 Tablepublic static void deleteRecord(Integer student_id) {try {// Getting Session Object From SessionFactorysessionObj = buildSessionFactory().openSession();// Getting Transaction Object From Session ObjectsessionObj.beginTransaction();Student studObj = findRecordById(student_id);sessionObj.delete(studObj);// Committing The Transactions To The DatabasesessionObj.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 Tablepublic static Student findRecordById(Integer find_student_id) {Student findStudentObj = null;try {// Getting Session Object From SessionFactorysessionObj = buildSessionFactory().openSession();// Getting Transaction Object From Session ObjectsessionObj.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 Tablepublic static void deleteAllRecords() {try {// Getting Session Object From SessionFactorysessionObj = buildSessionFactory().openSession();// Getting Transaction Object From Session ObjectsessionObj.beginTransaction();Query queryObj = sessionObj.createQuery("DELETE FROM Student");queryObj.executeUpdate();// Committing The Transactions To The DatabasesessionObj.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 theSessionFactory from the Hibernate configuration file and interacts with the DAO class to perform the CRUD operations. Add the following code to it:

Want to be a Hibernate Master ?
Subscribe to our newsletter and download the HibernateUltimateGuideright now!
In order to help you master JPA and database programming with Hibernate, we have compiled a kick-ass guide with all the major Hibernate features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

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 onsrc/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 asHibernateCrud/src/main/resources and enter the file name ashibernate.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 /></session-factory></hibernate-configuration>

Notes:

  • Here, we instructed Hibernate to connect to a MySQL database namedtutorialDb and the Mapping classes to be loaded
  • We have also instructed Hibernate framework to useMySQLDialect i.e. Hibernate will optimize the generatedSQL statements for MySQL
  • This configuration will be used to create a HibernateSessionFactory object

4. Run the Application

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

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

5. Project Demo

Executing theAppMain 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
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinAugust 24th, 2017Last Updated: February 20th, 2019
4 2,891 10 minutes read
Photo of Yatin

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
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.