Hibernate SessionFactory Class Example

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

Introduction

The SessionFactory is a crucial component in Hibernate and is responsible for creating Session instances. It is a factory for Session objects and is designed to be instantiated once per application, as it is thread-safe and expensive to create. In this tutorial, we will set up a Hibernate project and demonstrate the use of SessionFactory to manage Hibernate sessions.

In this tutorial, we will:

  1. Set up a Maven project with Hibernate and MySQL dependencies.
  2. Configure Hibernate.
  3. Create an entity class (Employee).
  4. Implement an example to demonstrate the use of SessionFactory.
  5. Demonstrate the SessionFactory usage using a sample application.

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://www.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>hibernate-sessionfactory-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>
    </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>

1.3 Configure Hibernate

Create a file named hibernate.cfg.xml in the src/main/resources directory to configure Hibernate. This file contains the 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 2: Create the Entity Class

Create an entity class Employee 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 Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String department;
    private double salary;

    // 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;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

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 3: Create the Hibernate Utility Class

Create a utility class HibernateUtil to manage the Hibernate SessionFactory. This class ensures a single instance of SessionFactory is created and provides a method to close it.

package com.example.util;

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

Explanation:

  • The buildSessionFactory method creates the SessionFactory from the hibernate.cfg.xml configuration file.
  • The getSessionFactory method returns the singleton instance of SessionFactory.
  • The shutdown method closes the SessionFactory to release resources.

Step 4: Demonstrate the Use of SessionFactory

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

package com.example.main;

import com.example.entity.Employee;
import com.example.util.HibernateUtil;
import org.hibernate.Session;

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

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

            // Perform some operation
            Employee employee = new Employee();
            employee.setName("John Doe");
            employee.setDepartment("IT");
            employee.setSalary(5000.00);
            session.save(employee);

            // Commit transaction
            session.getTransaction().commit();

            System.out.println("Employee saved successfully");

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

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

Explanation:

  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:

    session.beginTransaction();
    

    A transaction is started for the session.

  3. Perform Some Operation:

    Employee employee = new Employee();
    employee.setName("John Doe");
    employee.setDepartment("IT");
    employee.setSalary(5000.00);
    session.save(employee);
    

    An Employee entity is created and saved to the database.

  4. Commit Transaction:

    session.getTransaction().commit();
    

    The transaction is committed to persist the changes.

  5. Handle Exceptions:

    if (session.getTransaction() != null) {
        session.getTransaction().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:

Employee saved successfully

This output indicates that the employee was successfully saved using Hibernate's SessionFactory.

Conclusion

In this tutorial, we have successfully demonstrated how to use SessionFactory in Hibernate. We set up a Hibernate project, configured Hibernate, created an entity class, implemented a Hibernate utility class to manage SessionFactory, and demonstrated the use of SessionFactory with a sample application. This guide provides a solid foundation for managing Hibernate sessions using SessionFactory in your applications.


Comments