Singleton Hibernate SessionFactory Example

By |2019-05-04T10:58:26+05:30October 21st, 2015|Hibernate|

Hibernate SessionFactory is a crucial interface of Hibernate API. It is coming 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 hibernate framework, an only heavy object is a SessionFactory object. Because the SessionFactory builds 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:

To implement the Hibernate SessionFactory as a 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 for creating an object for utility class. 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());
    SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory();
    System.out.println("Session Factory 2 : " + sessionFactory2.hashCode());
    SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory();
    System.out.println("Session Factory 3 : " + sessionFactory3.hashCode());
  }
}
Output
Session Factory : 1574615832 
Session Factory 2 : 1574615832 
Session Factory 3 : 1574615832

On the above example, we declared the factory method with the synchronised keyword. Because in case, if the two threads call factory method precisely 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 synchronised 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+ ,

6 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

  5. tbil99@netscape.net'
    Tim May 2, 2019 at 3:12 am - Reply

    Should be –

    SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
    System.out.println(“Session Factory : ” + sessionFactory.hashCode());

    SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory();
    System.out.println(“Session Factory 2 : ” + sessionFactory2.hashCode());

    SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory();
    System.out.println(“Session Factory 3 : ” + sessionFactory3.hashCode());

  6. ashkanariaashkan@gmail.com'
    ashkan May 13, 2019 at 1:10 pm - Reply

    many thanks for this tutorial.

Leave A Comment