Singleton Hibernate SessionFactory Example

By | 2018-08-08T08:40:22+00:00 October 21st, 2015|Hibernate|4 Comments

Hibernate SessionFactory is a key interface of Hibernate API. It is comming from org.hibernate.SessionFactory package. The main goal of this interface is to provide the Hibernate Session instances.

Hibernate SessionFactory :

We can get the Hibernate SessionFactory object by calling the buildSessionFactory() method. Like below :

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

But the buildSessionFactory() method is deprecated from hibernate 4.x version. And it was replaced with the below syntax :

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());

In the whole hibernate framework, the one and only heavy object is SessionFactory object. Because the SessionFactory build with all the configuration information about the application.

Like below :

Configuration configuration = new Configuration().configure("hibernate.cfg.xml");

Recommended : The Complete CRUD Application of Hibernate.

So that in Hibernate SessionFactory, a configuration file and all the mapping data will be stored. In real time applications like spring with hibernate integration, per each client request if a separate SessionFactory is created then the performance of the application will be reduced. To improve the performance of an application, we need to make the Hibernate SessionFactory ‘s object as a singleton.

How to make the Hibernate SessionFactory as Singleton:

Typically, In order to implement the Hibernate SessionFactory as singleton, we create a separate class. Because this class is only responsible for making the Hibernate SessionFactory object as a singleton.

Usually, we call such type of classes as utility classes. In that utility class, we define a static factory method to a Hibernate SessionFactory object for one time and return the same factory object always.

Since the utility class is only responsible for creating the singleton Hibernate SessionFactory object and returning that object, there is no need of creating an object for utility class. In order to disallow to creating objects by other classes, we can make the utility class constructor as private.

Example For Hibernate SessionFactory :

HibernateUtility.java
package com.onlinetutorialspoint.config;

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

public class HibernateUtility {

    public static SessionFactory factory;
//to disallow creating objects by other classes.

    private HibernateUtility() {
    }
//maling the Hibernate SessionFactory object as singleton

    public static synchronized SessionFactory getSessionFactory() {

        if (factory == null) {
            factory = new Configuration().configure("hibernate.cfg.xml").
                    buildSessionFactory();
        }
        return factory;
    }
}

Main.java

Main.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.config.HibernateUtility;
import org.hibernate.SessionFactory;

public class Main {
  public static void main(String[] args) {
    SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
    System.out.println("Session Factory : " + sessionFactory.hashCode());
    System.out.println("Session Factory 2 : " + sessionFactory.hashCode());
    System.out.println("Session Factory 3 : " + sessionFactory.hashCode());
  }
}
Output
Session Factory : 1574615832 
Session Factory 2 : 1574615832 
Session Factory 3 : 1574615832


On the above example, we declared the factory method with synchronize keyword. Because in case, if the two threads calls factory method exactly at the same time then there is a chance of creating two Hibernate SessionFactory objects.

So, it is recommended to make the factory method as a synchronized method. And also we can find the same hashcode for all SessionFactory creations. Then we can say that our application will generate only single Hibernate SessionFactory instance and serve that instance for different client calls. Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

4 Comments

  1. vk74826@gmail.com'
    vicky December 25, 2016 at 9:50 am - Reply

    nice explanation.

  2. mamta.chaplot@gmail.com'
    Mamta December 29, 2016 at 9:33 am - Reply

    Please suggest the best way to create Sessionfactory

    There are many ways like one shown above

    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    SessionFactory factory = configuration.buildSessionFactory(builder.build());
    In the

    second using LocalSessionFactoryBean

    LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource());
    sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
    sessionFactoryBean.setHibernateProperties(hibernateProperties());
    return sessionFactoryBean;

    Please suggest which one should ne used

  3. a4arunraaj@gmail.com'
    arun singh May 3, 2017 at 7:24 pm - Reply

    Very nice explanation, sir

  4. pooja.bs@gmail.com'
    Pooja August 3, 2018 at 6:03 pm - Reply

    So damn helpful…Solved my nightmare

Leave A Comment