Tutorials  /  JavaScript

Hibernate SessionFactory

Ccentron Redaktion · December 2024 ·3 min read ·JavaScript, Tutorial

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

Hibernate SessionFactory

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

Hibernate getCurrentSession

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

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

If it’s not configured to thread, then we will get the following exception:

Code
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 them in a multi-threaded environment. We can use them in a single-threaded environment because it’s relatively faster than opening a new session.

Hibernate SessionFactory openSession

The 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 a 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 openStatelessSession

The Hibernate SessionFactory openStatelessSession() method returns an instance of StatelessSession. There is another overloaded method where we can pass a java.sql.Connection object to get a stateless session object from Hibernate. StatelessSession in Hibernate does not implement a first-level cache and 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 the Hibernate framework.

However, a stateless session can be a good fit in certain situations. For example, where we are loading bulk data into a database and we don’t want the Hibernate session to hold huge data in first-level cache memory. A simple program showing Hibernate SessionFactory methods usage is given below:

Go
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 its different methods to obtain session objects.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Conclusion

Hibernate SessionFactory is a powerful tool for managing database sessions. By understanding the differences between getCurrentSession(), openSession(), and openStatelessSession(), developers can choose the right approach based on their application's requirements, ensuring both performance and scalability.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren