I have some questions about using Hibernate in JSP web application.
-
What should be the value for
hibernate.current_session_context_class? -
Then, which of the following statements should be used? And why?
Session s = HibernateUtil.getSessionFactory().openSession(); Session s = HibernateUtil.getSessionFactory().getCurrentSession() -
Lastly, which one is better “one session per web app” or “one session per request”?
As explained in this forum post, 1 and 2 are related. If you set
hibernate.current_session_context_classto thread and then implement something like a servlet filter that opens the session – then you can access that session anywhere else by using theSessionFactory.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.If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.
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”