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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With