138

I have some questions about using Hibernate in JSP web application.

  1. What should be the value for hibernate.current_session_context_class?

  2. Then, which of the following statements should be used? And why?

     Session s = HibernateUtil.getSessionFactory().openSession();
     Session s = HibernateUtil.getSessionFactory().getCurrentSession()
    
  3. Lastly, which one is better "one session per web app" or "one session per request"?

0

6 Answers 6

154

As explained in this forum post, 1 and 2 are related. If you set 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.

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"

6
  • Thank you very much, @gkamal. I look at the code in Open Session in View document. (Your link points to that documents.) The author suggests the use of filter. In his filter code, he doesn't call openSession() or close(). He only calls getCurrentSession(). I guess he sets current_session_context to thread. Now I think I understand getCurrentSession(). However, I don't know when should I use openSession().
    – wannik
    Nov 8, 2011 at 11:51
  • 4
    You will use OpenSession if you don't want the session to be bound to any context. There are some situations when you would need a different session - other than one bound to the context (Hibernate Interceptors have a limitation that you can't use the original session) - in those cases you would use OpenSession instead of currentSession. OpenSession creates a new session which you have to close explicitly.For e.g., in a DAO method you will call OpenSession - use the session and close it.
    – gkamal
    Nov 8, 2011 at 12:12
  • am using getCurrentSession(); because i initialized it in listener not filter is this ok from your view; am using mvc2 jsp servlet
    – shareef
    May 13, 2013 at 21:24
  • @gkamal - I have a question related to Sessions. Can you please help me with it at - stackoverflow.com/questions/23351083/… . Thank you and chenqui. Apr 28, 2014 at 21:01
  • IMO, it is good practice to let each thread holds its own Session, and only one Session, right?
    – coderz
    Jun 27, 2016 at 15:23
34

If we talk about SessionFactory.openSession()

  • It always creates a new Session object.
  • You need to explicitly flush and close session objects.
  • In single threaded environment it is slower than getCurrentSession().
  • You do not need to configure any property to call this method.

And If we talk about SessionFactory.getCurrentSession()

  • It creates a new Session if not exists, else uses same session which is in current hibernate context.
  • You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.
1
  • 1
    The answer above tells not to use a single session per webapp. Thus if I were to use getCurrentSession, it would reuse the same sesssion, wouldn't it?
    – parsecer
    Dec 18, 2019 at 16:08
13

openSession: When you call SessionFactory.openSession, it always creates a new Session object and give it to you.

You need to explicitly flush and close these session objects.

As session objects are not thread safe, you need to create one session object per request in multi-threaded environment and one session per request in web applications too.

getCurrentSession: When you call SessionFactory.getCurrentSession, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope.

When you call SessionFactory.getCurrentSession, it creates a new Session if it does not exist, otherwise use same session which is in current hibernate context. It automatically flushes and closes session when transaction ends, so you do not need to do it externally.

If you are using hibernate in single-threaded environment , you can use getCurrentSession, as it is faster in performance as compared to creating a new session each time.

You need to add following property to hibernate.cfg.xml to use getCurrentSession method:

<session-factory>
    <!--  Put other elements here -->
    <property name="hibernate.current_session_context_class">
          thread
    </property>
</session-factory>
2
  • 1
    Doesn't a servlet open a new thread for each request? Thus if it's a Java webapp, it is already not a single-threaded environment?
    – parsecer
    Dec 18, 2019 at 16:10
  • @parsecer right? nobody's giving a practical example of when to use either. Apr 30, 2022 at 13:51
7
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter            |                                openSession                                 |                                          getCurrentSession                                          |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session  creation    | Always open new session                                                    | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close        | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed.    |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close      | Need to explicity flush and close session objects                          | No need to flush and close sessions , since it is automatically taken by hibernate internally.      |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance          | In single threaded environment , it is slower than getCurrentSession       | In single threaded environment , it is faster than openSession                                      |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration        | No need to configure any property to call this method                      | Need to configure additional property:                                                              |
|                      |                                                                            |  <property name=""hibernate.current_session_context_class"">thread</property>                       |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
0
currentSession -> to fetch the session

beginTransaction -> to open session commit and rollback -> to close session

1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 14, 2023 at 14:03
-7

SessionFactory: "One SessionFactory per application per DataBase" ( e.g., if you use 3 DataBase's in our application , you need to create sessionFactory object per each DB , totally you need to create 3 sessionFactorys . or else if you have only one DataBase One sessionfactory is enough ).

Session: "One session for one request-response cycle". you can open session when request came and you can close session after completion of request process. Note:-Don't use one session for web application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.