Spring + Hibernate session management across multiple threads

前端 未结 1 1798
无人共我
无人共我 2021-02-05 14:01

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 t

相关标签:
1条回答
  • 2021-02-05 14:27

    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.

    0 讨论(0)
提交回复
热议问题