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.