Hibernate Session Tutorial: save, persist, saveOrUpdate, get, load, merge, and delete Example

In this tutorial, we will explore various methods provided by the Hibernate Session interface using a Todo entity. These methods include save, persist, saveOrUpdate, get, load, merge, and delete.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • MySQL database installed and running (or any other relational database)
  • An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed

Step 1: Setting Up the Project

1.1 Create a Maven Project

  1. Open your IDE and create a new Maven project.

  2. Configure the pom.xml file with the following content:

<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.example</groupId>
    <artifactId>hibernate-session-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Hibernate and JPA -->
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.4.0.Final</version>
        </dependency>
        <dependency>
            <groupId>jakarta.persistence</groupId>
            <artifactId>jakarta.persistence-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!-- SLF4J for logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.32</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.32</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1.2 Configure Hibernate

Create a hibernate.cfg.xml file in the src/main/resources directory with the following content:

<!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.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database_name</property>
        <property name="hibernate.connection.username">your_username</property>
        <property name="hibernate.connection.password">your_password</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
    </session-factory>
</hibernate-configuration>

Replace your_database_name, your_username, and your_password with your MySQL database credentials.

Step 2: Creating the Entity Class

Create a Todo class in the com.example.hibernatecrud.model package:

package com.example.hibernatecrud.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Todo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String description;
    private boolean completed;

    // Getters and Setters
    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }
}

Step 3: Creating the Utility Class

Create a HibernateUtil class in the com.example.hibernatecrud.util package:

package com.example.hibernatecrud.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
            configuration.addAnnotatedClass(com.example.hibernatecrud.model.Todo.class);
            return configuration.buildSessionFactory(new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build());
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

Step 4: Using Hibernate Session Methods

4.1 Save

The save method generates a new identifier and inserts the entity into the database.

import com.example.hibernatecrud.model.Todo;
import com.example.hibernatecrud.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class SaveExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Todo todo = new Todo();
        todo.setTitle("Learn Hibernate");
        todo.setDescription("Study Hibernate save method");
        todo.setCompleted(false);

        session.save(todo);

        transaction.commit();
        session.close();
    }
}

4.2 Persist

The persist method makes an entity instance managed and persistent.

public class PersistExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Todo todo = new Todo();
        todo.setTitle("Learn Hibernate");
        todo.setDescription("Study Hibernate persist method");
        todo.setCompleted(false);

        session.persist(todo);

        transaction.commit();
        session.close();
    }
}

4.3 SaveOrUpdate

The saveOrUpdate method either saves a transient instance or updates an attached instance.

public class SaveOrUpdateExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Todo todo = new Todo();
        todo.setId(1L); // Assume this ID exists in the database
        todo.setTitle("Learn Hibernate");
        todo.setDescription("Study Hibernate saveOrUpdate method");
        todo.setCompleted(false);

        session.saveOrUpdate(todo);

        transaction.commit();
        session.close();
    }
}

4.4 Get

The get method retrieves an entity by its identifier.

public class GetExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Todo todo = session.get(Todo.class, 1L); // Assume this ID exists in the database

        if (todo != null) {
            System.out.println("Title: " + todo.getTitle());
        } else {
            System.out.println("Todo not found");
        }

        session.close();
    }
}

4.5 Load

The load method retrieves an entity by its identifier, but returns a proxy if the entity is not found.

public class LoadExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Todo todo = session.load(Todo.class, 1L); // Assume this ID exists in the database

        System.out.println("Title: " + todo.getTitle());

        session.close();
    }
}

4.6 Merge

The merge method copies the state of the given object onto the persistent object with the same identifier.

public class MergeExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Todo detachedTodo = new Todo

();
        detachedTodo.setId(1L); // Assume this ID exists in the database
        detachedTodo.setTitle("Learn Hibernate");
        detachedTodo.setDescription("Study Hibernate merge method");
        detachedTodo.setCompleted(true);

        Todo mergedTodo = (Todo) session.merge(detachedTodo);

        transaction.commit();
        session.close();
    }
}

4.7 Delete

The delete method removes the entity instance from the database.

public class DeleteExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Todo todo = session.get(Todo.class, 1L); // Assume this ID exists in the database
        if (todo != null) {
            session.delete(todo);
        }

        transaction.commit();
        session.close();
    }
}

Conclusion

In this tutorial, we explored various methods provided by the Hibernate Session interface using a Todo entity. These methods include save, persist, saveOrUpdate, get, load, merge, and delete. By following these examples, you can effectively manage data persistence in your Java applications using Hibernate.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare