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

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
wannik
  • 12,212
  • 11
  • 46
  • 58

6 Answers6

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"

Siddharth
  • 9,349
  • 16
  • 86
  • 148
gkamal
  • 20,777
  • 4
  • 60
  • 57
  • Thank you very much, @gkamal. I look at the code in [Open Session in View](http://community.jboss.org/wiki/OpenSessionInView) 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 08 '11 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 08 '11 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 '13 at 21:24
  • @gkamal - I have a question related to `Sessions`. Can you please help me with it at - https://stackoverflow.com/questions/23351083/understanding-sessionfactory-and-hibernate-sessions . Thank you and chenqui. – Erran Morad Apr 28 '14 at 21:01
  • IMO, it is good practice to let each thread holds its own Session, and only one Session, right? – coderz Jun 27 '16 at 15:23
  • @gkamal `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? – Sam YC Aug 23 '16 at 14:28
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.
Prashant Zombade
  • 482
  • 3
  • 15
Ramu Agrawal
  • 518
  • 6
  • 9
  • 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 '19 at 16:08
12

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>
Azeem
  • 11,148
  • 4
  • 27
  • 40
ngg
  • 1,493
  • 19
  • 14
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>                       |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
Joby Wilson Mathews
  • 10,528
  • 6
  • 54
  • 53
0
currentSession -> to fetch the session

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

Lobots
  • 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](/help/how-to-answer). – Community Jun 14 '23 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.

swamy
  • 67
  • 1
  • 4