Tuesday , November 21 2017
Home / Hibernate / Singleton Hibernate SessionFactory Example

Singleton Hibernate SessionFactory Example

 

Hibernate SessionFactory is a key interface of Hibernate API. The Hibernate SessionFactory interface is comes from org.hibernate.SessionFactory. 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 only heavy object is SessionFactory object. Because while configuring the application we need to give hibernate.cfg.xml file to configuration object. 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 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 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 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 :


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


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 factory method as a synchronize 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.

About chandrashekhar

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

Recommended

Hibernate Native SQL Query Example

In this tutorials, we are going to learn about Hibernate Native SQL with example. Hibernate …

3 comments

  1. vk74826@gmail.com'

    nice explanation.

  2. mamta.chaplot@gmail.com'

    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'

    Very nice explanation, sir

Leave a Reply

Your email address will not be published. Required fields are marked *