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()?
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
ThreadLocalobject. 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 withsf.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 remembersf.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.