Spring + Hibernate session management across multiple threads

13,256

Yes. It is enough.

When setting hibernate.current_session_context_class to thread , the session returned from SessionFactory.getCurrentSession() is from the ThreadLocal instance.

Every thread will have their own, independently ThreadLocal instance, so different threads will not access to the same hibernate session.

The behaviour of SessionFactory.getCurrentSession() is that: if it is called for the first time in the current thread, a new Session is opened and returned. If it is called again in the same thread, the same session will be returned.

As a result , you can get the same session to use in different DAO methods in the same transaction code by simply calling SessionFactory.getCurrentSession(). It prevents you from passing the Hibernate session through the DAO method 's input parameters in the case that you have to call many different DAO methods in the same transaction code.

Share:
13,256

Related videos on Youtube

Laimoncijus
Author by

Laimoncijus

Updated on June 04, 2022

Comments

  • Laimoncijus
    Laimoncijus almost 2 years

    I am building a system, where each request from a client side spawns multiple threads on server side. Each thread then is using one or more DAOs (some DAOs can be used by more than one thread at the time). All DAOs are injected (@Autowired) to my thread classes by Spring. Each DAO receives SessionFactory injected as well.

    What would be proper way of managing Hibernate sessions across these multiple DAOs so I would not run into problems because of multithreaded environment (e.g. few DAOs from different threads are trying to use the same session at the same time)?

    Would be enough that I specify hibernate.current_session_context_class=thread in Hibernate configuration and then everytime in DAO simply use SessionFactory.getCurrentSession() to do the work? Would it properly detect and create sessions per thread as needed?

  • MounirReg
    MounirReg about 10 years
    What about closing the session when the work is done, is it done automatically ?
  • UCJava
    UCJava over 8 years
    When you are Hibernate with Spring 3 or later you should avoid setting this property since Spring has it's own implementation of this that is necessary for Spring to manage Hibernate sessions. stackoverflow.com/a/18842593/3826713