Tuesday, 4 December 2012

Difference between Session.openSession() & Session.getCurrentSession()


  1. What should be the value for hibernate.current_session_context_class?
  2. Session s = HibernateUtil.getSessionFactory().openSession();
    Session s = HibernateUtil.getSessionFactory().getCurrentSession()
Which one is better "one session per web app" or "one session per request"?

hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

SessionFactory.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.

You should never use "one session per web app" - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

GetSession gives you a Hibernate session, and associates that session with the current thread. Then, if you call getSession again, you get the session that was originally created. This is good.

Some people don't like binding the Hibernate Session to the current thread, and they don't like the ease of getting the current Session back with getSession. Instead, these people use openSession, which creates a new Session and asks the DEVELOPER to manage where the session goes. I gues you could put it in a list or a cache, or whatever, but YOU must manage it, as though you were creating your own database connection pool or something.

getSession is usually sufficient. openSession provides and facilitates a greater level of management of where the session is stored and managed. It's certainly an advanced option, but one that does indeed fit the need of very clever developers who are doing some nifty things with the session.

Some people who are much better looking than me, not to mention being much more intelligent, discussed just this topic in the following JavaRanch thread:

No comments:

Post a Comment