Tutorial

Hibernate SessionFactory

Published on August 3, 2022
author

Pankaj

Hibernate SessionFactory

Hibernate SessionFactory is the factory class through which we get sessions and perform database operations.

Hibernate SessionFactory

hibernate sessionfactory Hibernate SessionFactory provides three methods through which we can get Session object - getCurrentSession(), openSession() and openStatelessSession().

Hibernate SessionFactory getCurrentSession

Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file like below.

<property name="hibernate.current_session_context_class">thread</property>

If its not configured to thread, then we will get below exception.

Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
	at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)
	at com.journaldev.hibernate.main.HibernateSessionExample.main(HibernateSessionExample.java:16)

Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed. Hibernate Session objects are not thread safe, so we should not use it in multi-threaded environment. We can use it in single threaded environment because it’s relatively faster than opening a new session.

Hibernate SessionFactory openSession

Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment. For web application frameworks, we can choose to open a new session for each request or for each session based on the requirement.

Hibernate SessionFactory openStatelessSession

Hibernate SessionFactory openStatelessSession() method returns instance of StatelessSession. There is another overloaded method where we can pass java.sql.Connection object to get a stateless session object from hibernate. StatelessSession in Hibernate does not implement first-level cache and it doesn’t interact with any second-level cache. Since it’s stateless, it doesn’t implement transactional write-behind or automatic dirty checking or do cascading operations to associated entities. Collections are also ignored by a stateless session. Operations performed via a stateless session bypass Hibernate’s event model and interceptors. It’s more like a normal JDBC connection and doesn’t provide any benefits that come from using hibernate framework. However, stateless session can be a good fit in certain situations. For example where we are loading bulk data into database and we don’t want hibernate session to hold huge data in first-level cache memory. A simple program showing Hibernate SessionFactory methods usage is given below.

package com.journaldev.hibernate.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;

import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateSessionExample {

	public static void main(String[] args) {
		
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		
		//Current Session - no need to close
		Session currentSession = sessionFactory.getCurrentSession();
		
		//open new session
		Session newSession = sessionFactory.openSession();
		//perform db operations
		
		//close session
		newSession.close();
		
		//open stateless session
		StatelessSession statelessSession = sessionFactory.openStatelessSession();
		//perform stateless db operations
		
		//close session
		statelessSession.close();
		
		//close session factory
		sessionFactory.close();
		
	}

}

That’s all for SessionFactory in Hibernate and it’s different methods to obtain session object.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 5, 2021

Hi Pankaj, Your explanation put me into curiosity that how in multithreading, getCurrentSeasson method will create problem . can anyone explain? I do some research but could not find any relevand blog for that

- Amit Sarkar

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 26, 2018

    Hi i’m getting deleted data in my service response can you help me what can be the solution for that.and also some time alternate time data is coming and not coming.

    - Sabndeep Kumar Prasad

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 16, 2015

      Hi Pankaj, When I am using sessionFactory.getCurrentSession() and create criteria query, Its give me error has “createCriteria is not valid without active transaction”

      - farhan

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 27, 2015

        Using getCurrentSession(), we cannot perform lazy loading whereas openSession supports lazy loading

        - Vishwas

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 28, 2015

          Hi Pankaj, What I interpret from article that hibernate CurrentSession() is not thread safe only and rest two OpenSession() and OpenStatelessSession() are thread safe. Can you please confirm?

          - manish gupta

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 25, 2015

            Hi pankaj, You have really explained the concepts very well.It was really helpful going through this website.If you can avoid more technical and use simple words it will be still easier to understand the concepts.Thanks a lot for sharing your knowledge.

            - nagesh

              Try DigitalOcean for free

              Click below to sign up and get $200 of credit to try our products over 60 days!

              Sign up

              Join the Tech Talk
              Success! Thank you! Please check your email for further details.

              Please complete your information!

              Become a contributor for community

              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

              DigitalOcean Documentation

              Full documentation for every DigitalOcean product.

              Resources for startups and SMBs

              The Wave has everything you need to know about building a business, from raising funding to marketing your product.

              Get our newsletter

              Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

              New accounts only. By submitting your email you agree to our Privacy Policy

              The developer cloud

              Scale up as you grow — whether you're running one virtual machine or ten thousand.

              Get started for free

              Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

              *This promotional offer applies to new accounts only.