My Quotes

When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go

Thursday, June 5, 2014

Hibernate getCurrentSession() versus openSession()

  • getCurrentSession()
  • this means that you have ONE session for the whole web app.
  • Bear in mind, Sessions are not THREAD SAFE.
  • 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".
  • The advantage is returns a session bound to a context - you don't need to close this
  • SessionFactory.openSession()
  • always opens a new session that you have to close once you are done with the operations.
  • If you are using Spring to manage transactions you can configure them to open / close sessions along with the transactions

          Private Session sessionObj = null;
           private Session getHibSession() throws ORMException {
                  SessionFactory sessionFactObj = null;
                  try {
                         if (sessionObj != null) {
                               return sessionObj;
                         } else {
                               sessionFactObj = HibernateSessionFactory.getInstance().getSessionFactory(hibernateConfig);
                               sessionObj = sessionFactObj.openSession();
                               return sessionObj;
                  } catch (HibernateException hibex) {
                         throw new Exception(hibex);
                  } catch (RuntimeException rte) {
                         throw new Exception(rte);
  • No comments :