17

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()?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
tintin
  • 5,676
  • 15
  • 68
  • 97

1 Answers1

37

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.

Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96
  • 1
    Does that mean that if I am using sf.getCurrentSession for multithreads inside tomcat - it will use the same session? is it ok? – Dejell Jun 09 '15 at 17:32