Hibernate openSession() vs getCurrentSession()
Asked Answered
S

6

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"?

Scatterbrain answered 8/11, 2011 at 6:20 Comment(0)
C
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"

Christology answered 8/11, 2011 at 10:49 Comment(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().Scatterbrain
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.Christology
am using getCurrentSession(); because i initialized it in listener not filter is this ok from your view; am using mvc2 jsp servletNarwhal
@Christology - I have a question related to Sessions. Can you please help me with it at - #23351583 . Thank you and chenqui.Psalmbook
IMO, it is good practice to let each thread holds its own Session, and only one Session, right?Woodrowwoodruff
@Christology SessionFactory.openSession() if I use this in Transaction context, do I need to manage the connection myself? When I use this, will the auto-commit set to false? so when I do UserTransaction.commit, Transaction Manager will help me commit or rollback?Acuate
P
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.
Pickel answered 17/11, 2016 at 7:48 Comment(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?Overlay
F
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>
Feeble answered 17/8, 2017 at 11:22 Comment(2)
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?Overlay
@Overlay right? nobody's giving a practical example of when to use either.Daley
N
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>                       |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
Negotiation answered 11/3, 2020 at 13:46 Comment(0)
C
0
currentSession -> to fetch the session

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

Clandestine answered 12/6, 2023 at 21:12 Comment(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.Freshen
N
-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.

Niigata answered 22/10, 2014 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.