Hibernate SessionFactory | Singleton | SessionFactory

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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.
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.
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());
    SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory();
    System.out.println("Session Factory 2 : " + sessionFactory2.hashCode());
    SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory();
    System.out.println("Session Factory 3 : " + sessionFactory3.hashCode());
  }
}
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 🙂

hibernate update query example
Hibernate Left Join Example
Hibernate session differences between load() and get()
Custom Generator Class in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Right Join Example
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Top 10 Advantages of Hibernate
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
Hibernate cache first level example
Table per Class Strategy in Hibernate Inheritance

hibernate update query example
Hibernate Left Join Example
Hibernate session differences between load() and get()
Custom Generator Class in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Right Join Example
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Top 10 Advantages of Hibernate
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
Hibernate cache first level example
Table per Class Strategy in Hibernate Inheritance






vicky
December 25, 2016 at 9:50 am - Reply 

nice explanation.









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









arun singh
May 3, 2017 at 7:24 pm - Reply 

Very nice explanation, sir









Pooja
August 3, 2018 at 6:03 pm - Reply 

So damn helpful...Solved my nightmare









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());









ashkan
May 13, 2019 at 1:10 pm - Reply 

many thanks for this tutorial.










vicky
December 25, 2016 at 9:50 am - Reply 

nice explanation.




nice explanation.





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




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





arun singh
May 3, 2017 at 7:24 pm - Reply 

Very nice explanation, sir




Very nice explanation, sir





Pooja
August 3, 2018 at 6:03 pm - Reply 

So damn helpful...Solved my nightmare




So damn helpful...Solved my nightmare





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());




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());





ashkan
May 13, 2019 at 1:10 pm - Reply 

many thanks for this tutorial.




many thanks for this tutorial.
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache