Updated March 31, 2023
Introduction to Hibernate SessionFactory
Hibernate SessionFactory is an interface. It can be created through providing objects of Configuration. This will contain all the database property details which are pulled from either hibernate.properties file or hibernate.cfg.xml file. Session objects consist and are like a factory in SessionFactory. In any application, one can create an implementation of one sessionFactory per each database. If the application refers to multiple such databases, then one needs to create a SessionFactory per each database.
This is considered as a heavy weight object. During application startup, this is created and is kept for usage. It is a thread-safe object used by the threads of the application.
Syntax:
Syntax of Hibernate SessionFactory to getCurrentSession:
< property name = " hibernate.current_session_class">thread</property>
How Hibernate SessionFactory Works?
If the above is configured to the thread, we might get the below labelled 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)
As the object of the session belongs to a hibernate context, we don’t have to close it. The session object gets closed, once the sessionFactory gets closed.
Session objects of hibernate are never thread safe. This is why we shouldn’t use it in a multi-threaded environment but can be used in a single-threaded environment. Also, it is relatively faster to open a new session.
Return the associated Transaction object, by beginning the unit. | Transaction beginTransaction() |
Cancel the execution of the current query. | void cancelQuery() |
Completely clear the session. | void clear() |
Release the JDBC connection and clean up by ending the session | Connection close() |
With the identifier of the given detached instance, update the instance persistence. | void update(String entityName, Object object) |
With the identifier of the given detached instance, persistent instance is updated. | void update(Object object) |
Either save(Object) or update(Object) the given instance. | void saveOrUpdate(Object object) |
By first assigning a generated identifier, Persist the given transient instance. | Serializable save(Object object) |
Check if the session is still open. | boolean isOpen() |
Check if the session contains any changes which have to be synchronized with the databases. | boolean isDirty() |
Check if the session is currently connected. | boolean isConnected() |
Transaction instance is noticed which is associated with the session. | Transaction getTransaction() |
From the underlying specific database, one shall re-read the condition of the given database. | void refresh(Object object) |
SessionFactory creator of this session is returned. | SessionFactory getSessionFactory() |
With the given entity and identifier name, return of persistent instance is done and or or is nullified if no such instance of persistence is seen. | Session get(String entityName, Serializable id) |
Remove a persistent instance from the datastore. | void delete(String entityName, Object object) |
Remove a persistent instance from the datastore. | void delete(Object object) |
SQL query of new instance is created with the given string in SQL query | SQLQuery createSQLQuery(String queryString) |
HQL query of new instance is created with the given string in HQL query | Query createQuery(String queryString) |
For the assigned collection and string filter, create a new query instance. | Query createFilter(Object collection, String queryString) |
Value of the identifier of the mentioned entity is returned, in association with the session. | Serializable getIdentifier(Object object) |
For specified entity names, create an instance Criteria query. | Criteria createCriteria(String entityName) |
Criteria instance is created for the specified entity class or the superclass of an entity class. | Criteria createCriteria(Class persistentClass) |
Example
Example for Hibernate SessionFactory is given below :
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;
}
}
// The Main (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 :
The factory method is declared with a synchronised keyword. The two threads call the factory method of factory at the same time, which makes it possible for creating objects of hibernate SessionFactory
Conclusion
A sessionFactory object represents a single database or datastore. It is a thread safe object. It is built only once at the start of an application. Once we have a session, we can do all the thread operations – create, delete, modify, read, update and other. We can request a sessionFactory to us as many sessions as we need in the application.
Recommended Articles
This is a guide to Hibernate SessionFactory. Here we also discuss how hibernate sessionfactory works? along with different examples and its code implementation. You may also have a look at the following articles to learn more –