Open In App

CRUD Operations using Hibernate

Last Updated : 26 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Hibernate is a powerful Java ORM (Object-Relational Mapping) framework that simplifies database interactions by mapping Java objects to relational tables. It allows developers to perform CRUD operations (Create, Read, Update, Delete) without writing complex SQL queries.

In this article, we will cover:

  • Setting up Hibernate with MySQL
  • Performing CRUD operations with Hibernate
  • Using SessionFactory for database transactions

CRUD refers to database operations:

  • C -> Create/Insert
  • R -> Retrieve
  • U -> Update
  • D -> Delete

Given below are the examples that illustrate the use of Hibernate to perform CRUD operations. All the examples use MySQL for database management and ‘student_info’ as a sample database.

Project Setup

Step 1: Create SessionFactoryProvider class

This class creates and returns a SessionFactory object.

SessionFactoryProvider.java:

Java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryProvider {
    public static SessionFactory provideSessionFactory() {
        Configuration config = new Configuration();
        // Configures Hibernate with hibernate.cfg.xml
        config.configure();  
        return config.buildSessionFactory();
    }
}


Step 2: Create a POJO Class

Let’s create a POJO Class, this class represents the object persistent in the database.

Student.java:

Java
import javax.persistence.*;

@Entity
public class Student {
    @Id
    private int id;
    private String name;
    private int std;

    public Student() {
    }

    public Student(int id, String name, int std) {
        this.id = id;
        this.name = name;
        this.std = std;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStd() {
        return std;
    }

    public void setStd(int std) {
        this.std = std;
    }
}


Step 3: Create Configuration file:

This configuration file provides database connection details, mapping resources, etc. In this file, the hibernate.hbm2ddl.auto property is set to create for creating tables in the database automatically. If the table already exists in the database, the property is set to update to alter the existing schema.

hibernate.cfg.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student_info?serverTimezone=UTC</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <mapping class="Student"></mapping>  
    </session-factory>
</hibernate-configuration>


Inserting, Retrieving, Updating, and Deleting Records

Creating a Table and Inserting a New Record:

The following method, session.saveOrUpdate(), is used to insert or update the object in the database.

Create.java:

Java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utilities.SessionFactoryProvider;

public class Create {
    public static void main(String[] args) {
        SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();

        Student s = new Student(101, "John", 10);
        // Save or update the student record
        session.saveOrUpdate(s);  
        t.commit();

        session.close();
        sessionFactory.close();
    }
}

This code will insert the new record into the student_info table.

student table


Retrieving data from the database:

The following methods are used to retrieve the data from the database:

  • get(): Returns null if the object doesn’t exist in the database.

<T> T  get(Class<T> entityType, Serializable id)

  • load(): Throws ObjectNotFoundException if the object doesn’t exist in the database.

<T> T load(Class<T> theClass, Serializable id)


get() vs load()

The below table demonstrates the difference between get() and load().

get()

load()

It returns null if the object doesn’t exist in the database or session cache.It throws ObjectNotFoundException if the object doesn’t exist in the database or session cache.
It returns fully initialized objects which may require multiple database classes. Therefore it affects the performance of the application.It returns a proxy object and initializes the object only if any method is called on the object(other than getId()). Therefore it results in better performance.
get() is used to fetch an object when it is not sure whether the object exists or not.load() is used to fetch an object if it is sure that object exists.

Retrieve.java:

Java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utilities.SessionFactoryProvider;

public class Retrieve {
    public static void main(String[] args)
    {
        SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory();
        Session session=sessionFactory.openSession();
        
        Student s=session.get(Student.class, 101);
        System.out.println("Id : "+s.getId());
        System.out.println("Name : "+s.getName());
        System.out.println("Class : "+s.getStd());
        
        sessionFactory.close();
    }

}

The following details will be fetched from the database:

Student record


If an object doesn’t exist in database, get() returns null whereas load() throws ObjectNotFoundexception.

Retrieve.java: 

Java
package crudOperations;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import beans.Student;
import utilities.SessionFactoryProvider;

public class Retrieve {
    public static void main(String[] args) {
        SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory();
        Session session = sessionFactory.openSession();

        // Fetching object using get()
        System.out.println("Fetching object using get:");
        Student s1 = session.get(Student.class, 102);
        if (s1 != null) {
            System.out.println("Id: " + s1.getId());
            System.out.println("Name: " + s1.getName());
            System.out.println("Class: " + s1.getStd());
        } else {
            System.out.println("Student not found.");
        }

        sessionFactory.close();
    }
}


Output:

get() vs load()


Updating a record in the database:

Update.java:

Java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utilities.SessionFactoryProvider;

public class Update {
    public static void main(String[] args) {
        SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();

        Student s = session.get(Student.class, 101);
          // Update the student's grade
        s.setStd(11);
         // Save the updated student record
        session.saveOrUpdate(s); 
        t.commit();

        session.close();
        sessionFactory.close();
    }
}


The following record will be updated:

Student table


Deleting a record from the database:

To delete an object from the database, the session.delete() method is used.

Delete.java:

Java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import beans.Student;
import utilities.SessionFactoryProvider;

public class Delete {
    public static void main(String[] args) {
        SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();

        Student s = session.get(Student.class, 101);
        // Delete the student record
        session.delete(s);  
        t.commit();

        session.close();
        sessionFactory.close();
    }
}

Output:

Student table

Next Article
Article Tags :

Similar Reads