Hibernate Session persist Method Example

This tutorial will guide you through setting up and demonstrating the use of the session.persist method in Hibernate 6.4 using a MySQL database. We will use the Student entity for this example.

Introduction

The session.persist method is the recommended alternative to the deprecated session.save method in Hibernate. The persist method is part of the JPA specification and provides better compatibility with future versions of Hibernate. This tutorial will demonstrate the use of session.persist.

In this tutorial, we will:

  1. Set up a Maven project with Hibernate and MySQL dependencies.
  2. Configure Hibernate.
  3. Create an entity class (Student).
  4. Demonstrate the use of the session.persist method.

Step 1: Set Up Your Project

1.1 Create a Maven Project

Open your IDE and create a new Maven project.

1.2 Add Dependencies

Update your pom.xml file to include the necessary dependencies for Hibernate and MySQL.

<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-persist-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Hibernate ORM -->
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.4.0.Final</version>
        </dependency>

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

        <!-- Spring Context for Dependency Injection -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.13</version>
        </dependency>
    </dependencies>

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

Step 2: Configure Hibernate

2.1 Create hibernate.cfg.xml

Create a hibernate.cfg.xml file in the src/main/resources directory to configure database connection settings and Hibernate properties.

<!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/hibernate_db</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Replace hibernate_db, root, and password with your MySQL database name and credentials.

Explanation:

  • hibernate.dialect specifies the SQL dialect to be used.
  • hibernate.connection.driver_class specifies the JDBC driver class.
  • hibernate.connection.url specifies the JDBC URL for the database connection.
  • hibernate.connection.username and hibernate.connection.password specify the database credentials.
  • hibernate.hbm2ddl.auto specifies the schema generation strategy.
  • hibernate.show_sql specifies whether to show SQL statements in the logs.

Step 3: Create the Entity Class

Create an entity class Student that will be mapped to a table in the database. This class uses annotations to define the entity and its fields.

package com.example.entity;

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

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String department;

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

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

    public String getName() {
        return name;
    }

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

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }
}

Explanation:

  • The @Entity annotation specifies that the class is an entity and is mapped to a database table.
  • The @Id annotation specifies the primary key of the entity.
  • The @GeneratedValue(strategy = GenerationType.IDENTITY) annotation specifies that the primary key is auto-incremented.

Step 4: Demonstrate session.persist

Create a MainApp class to demonstrate the use of the session.persist method. This class initializes the SessionFactory, opens a session, performs an operation using session.persist, and then closes the session and shuts down the SessionFactory.

package com.example.main;

import com.example.entity.Student;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class MainApp {
    public static void main(String[] args) {
        // Get the SessionFactory
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            // Begin transaction
            transaction = session.beginTransaction();

            // Perform some operation using session.persist
            Student student = new Student();
            student.setName("Alice Johnson");
            student.setDepartment("Computer Science");
            session.persist(student); // Recommended method

            // Commit transaction
            transaction.commit();

            System.out.println("Student saved successfully using session.persist");

        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }

        // Shut down Hibernate
        HibernateUtil.shutdown();
    }
}

Explanation of the Code in Step 4

  1. Get the SessionFactory:

    Session session = HibernateUtil.getSessionFactory().openSession();
    

    The getSessionFactory method of HibernateUtil is called to obtain the SessionFactory, and a new session is opened.

  2. Begin Transaction:

    transaction = session.beginTransaction();
    

    A transaction is started for the session.

  3. Perform Some Operation Using session.persist:

    Student student = new Student();
    student.setName("Alice Johnson");
    student.setDepartment("Computer Science");
    session.persist(student); // Recommended method
    

    A Student entity is created and saved to the database using the session.persist method.

  4. Commit Transaction:

    transaction.commit();
    

    The transaction is committed to persist the changes.

  5. Handle Exceptions:

    if (transaction != null) {
        transaction.rollback();
    }
    

    If an exception occurs, the transaction is rolled back.

  6. Close the Session:

    session.close();
    

    The session is closed to release resources.

  7. Shut Down Hibernate:

    HibernateUtil.shutdown();
    

    The shutdown method of HibernateUtil is called to close the SessionFactory and release resources.

Sample Output

When you run the MainApp class, you should see the following output:

Student saved successfully using session.persist

This output indicates that the student was successfully saved using the session.persist method.

Conclusion

In this tutorial, we have successfully demonstrated how to use the session.persist method in Hibernate. We set up a Hibernate project, configured Hibernate, created an entity class, and demonstrated the use of the session.persist method with a sample application. The persist method is the recommended approach for saving entities in Hibernate and provides better compatibility with future versions of Hibernate.


Comments