Table of contents
1.
Introduction
2.
Session Object
3.
openSession() Method
4.
getCurrentSession() Method
5.
openSession Vs getCurrentSession Methods
6.
Frequently Asked Questions
6.1.
What is a Persistent Entity?
6.2.
What is a Detached Entity?
6.3.
What is lazy loading in Hibernate Architecture?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Difference between openSession and getCurrentSession

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Hibernate, we can use two methods to get the org.hibernate.Session object. These are using openSession() method and getCurrentSession() method. openSession() On each call,  openSession() method will return a new session object, which is an instance of org.hibernate.impl.SessionImpl. The current session is obtained using the getCurrentSession() method. The "current session" refers to a Hibernate Session that Hibernate has connected to the transaction scope behind the scenes.

Session Object

The Session object is created on-demand. A session is a lightweight object. Session object allows your application and database to communicate physically. The Session will be created each time your application wishes to interact with the database. SessionFactory will supply the Session object. The Session object will save and retrieve all persistent objects. After using the session object, it must be destroyed.

openSession() Method

When you call SessionFactory.openSession, it creates a new Session object and returns it to you. These session objects must be explicitly flushed and closed. Because session objects are not thread-safe, you must construct one session object for each request in a multithreaded environment and one session for each request in web applications.

private SessionImpl openSession(
   Connection connection,
       boolean autoClose,
       long timestamp,
       Interceptor sessionLocalInterceptor
   ) {
   return new SessionImpl(
      connection,
      this,
      autoClose,
      timestamp,
      sessionLocalInterceptor == null ? interceptor : sessionLocalInterceptor,
      settings.getDefaultEntityMode(),
      settings.isFlushBeforeCompletionEnabled(),
      settings.isAutoCloseSessionEnabled(),
      settings.getConnectionReleaseMode()
  );
}
You can also try this code with Online Java Compiler
Run Code

getCurrentSession() Method

When you call SessionFactory.getCurrentSession, will return a session object in hibernation context and is controlled internally by hibernate. It is restricted to transaction scope.

When you call SessionFactory.getCurrentSession, it produces a new Session if one does not already exist. Otherwise, it uses the session now in the hibernate context. When a transaction ends, it immediately flushes and closes the session, so you don't have to do anything else. If you are using hibernation in a single-threaded environment, you can use getCurrentSession, which is faster than generating a new session each time.

Transaction transaction = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try {
  transaction = session.beginTransaction();
  // do Some work
           
  // session.flush(); // no need
  transaction.commit();           
} catch(Exception ex) {           
  if(transaction != null) {
      transaction.rollback();
  }
  ex.printStackTrace();
} finally {
if(session != null) {
  // session.close(); // no need   
 }           
}
You can also try this code with Online Java Compiler
Run Code

openSession Vs getCurrentSession Methods

openSession and getCurrentSession methods have different characteristics when measured on various parameters.

1. Session Object: openSession always generates a new Session object, whereas getCurrentSession creates a new Session if one does not already exist, else, it utilizes the same session that is in the current hibernate context.

2. Flush and Close Operations: openSession explicitly flushes and closes session objects, whereas getCurrentSession does not need to flush or close session objects. Hibernate will do it internally.

3. Configuration: To call openSession, no other property configurations are required, while to call getCurrentSession, an additional property "hibernate.current_session_context_class" must be configured, else exceptions will be thrown.

4. Performance: openSession is slower than the getCurrentSession method in execution in a single threaded environment.

Frequently Asked Questions

What is a Persistent Entity?

A persistent entity represents one row of the database and is always related to some unique hibernate session. Changes to persistent objects are tracked by Hibernate and are saved into the database when commit calls occur. 

What is a Detached Entity?

A Detached Entity is one that was once Persistent in the past, and now it is no longer persistent. To persist changes done in detached objects, they must be re-attached to the hibernate session. 

What is lazy loading in Hibernate Architecture?

The Lazy setting determines whether child items are loaded while the Parent Object is loaded. You must achieve this by modifying the parent class's hibernate mapping file. Lazy = True (means not to load child) The sluggish loading of child objects is enabled by default.

Conclusion

This blog discussed the openSession and getCurrentSession methods in hibernate, their implementations, and their differences.

Congratulations on reaching the end. Hope you liked the blog, and it has added some new information to your coding journey. Please look at these similar topics to learn more: Java Interview QuestionsOOPS in JavaEncapsulation in Java, JDBCJDBC ConnectionGuide to ORMSpring Boot JDBC.

Recommended Reading:

Difference Between List and Set

Refer to our Coding Ninjas Studio Guided Path to learn Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and even more! You can also check out the mock test series and participate in the contests hosted by Coding Ninjas Studio! But if you're just starting and want to learn about questions posed by tech giants like Amazon, Microsoft, Uber, and so on. In such a case, for placement preparations, you can also look at the problemsinterview experiences, and interview bundle.

You can also consider our premium courses to offer your career advantage over others!

Please upvote our blogs if you find them useful and exciting!

Happy Coding!

Live masterclass