Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using openSession() over getCurrentSession() - when and why?

This question is in relation to another question I have asked, but what are the reasons as to why you would use openSession() over getCurrentSession()? I know you would use openSession() so that you could self-manage the closing and flushing of the session, however, why would you want to do this manually?

I have used openSession() when I wanted to perform a transaction in isolation to the current session though I am not sure if this is a correct use of openSession().

Why would you want multiple sessions open?

like image 309
digiarnie Avatar asked Oct 31 '10 00:10

digiarnie


People also ask

What is the difference between getCurrentSession () and openSession ()?

openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory. getCurrentSession() returns a session bound to a context - you don't need to close this.

What is used to open session in Hibernate?

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.

What is difference between session and session factory?

The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. The SessionFactory is a thread safe object and used by all the threads of an application. A Session is used to get a physical connection with a database.

Which creates new session even if a session already exists?

getCurrentSession() is called for the first time. This creates a brand new session if one does not exist or uses an existing one if one already exists.


1 Answers

I know you would use openSession() so that you could self-manage the closing and flushing of the session, however, why would you want to do this manually?

One would use openSession() to implement long conversations (i.e. when you want to use use a single Session for several database transactions aka the extended Session pattern).

I have used openSession() when I wanted to perform a transaction in isolation to the current session though I am not sure if this is a correct use of openSession().

Hmm... What? Transaction and Session are different concepts. What do you mean exactly?

Why would you want multiple sessions open?

That's not the intention.

References

  • Hibernate Core Reference Documentation
    • 11.1.2. Long conversations
  • Hibernate Wiki
    • Sessions and transactions
like image 94
Pascal Thivent Avatar answered Sep 29 '22 10:09

Pascal Thivent