I'm a little confused between the two. As per I know both returns hibernate session, SessionFactory.getCurrentSession()
returns a contextual session based on the property <property name="current_session_context_class">
which is set in hibernate.cfg.xml
Shouldn't we always go with this approach?
What additional value is added by SessionFactory.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.
SessionFactory is a factory class for Session objects. It is available for the whole application while a Session is only available for particular transaction. Session is short-lived while SessionFactory objects are long-lived. SessionFactory provides a second level cache and Session provides a first level cache.
The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations.
A session is opened whenever sf.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.
In Tomcat this associates a session with a thread which is created using the underlying ThreadLocal
object. But since Tomcat uses thread pooling it is entirely possible that a request may receive a thread with a session already associated with it, thus introducing the possibility of not even creating a brand new session. Another thing is that The Session that you obtained with sf.getCurrentSession()
is flushed and closed automatically.
The method sf.openSession()
on the other hand creates a new session but does not attempt to associate it with a thread. But remember sf.openSession()
introduces another hitch in that it expects users to handle the closing and flushing of sessions themselves, instead of letting Hibernate do it automatically for us.
sf.getCurrentSession()
is usually sufficient. sf.openSession()
provides and facilitates a greater level of management of where the session is stored and managed. It's certainly an advanced option.
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