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.


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"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://www.apache.org/xsd/maven-4.0.0.xsd">


        <!-- Hibernate ORM -->

        <!-- MySQL Connector -->


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"

        <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>

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


  • 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;

public class Employee {
    @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;


  • 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


  • 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

            // Perform some operation
            Employee employee = new Employee();
            employee.setName("John Doe");

            // Commit transaction

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

        } catch (Exception e) {
            if (session.getTransaction() != null) {
        } finally {

        // Shut down Hibernate


  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:


    A transaction is started for the session.

  3. Perform Some Operation:

    Employee employee = new Employee();
    employee.setName("John Doe");

    An Employee entity is created and saved to the database.

  4. Commit Transaction:


    The transaction is committed to persist the changes.

  5. Handle Exceptions:

    if (session.getTransaction() != null) {

    If an exception occurs, the transaction is rolled back.

  6. Close the Session:


    The session is closed to release resources.

  7. Shut Down Hibernate:


    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.


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.