Spring和Hibernate整合事务配置之current_session_context_class

1、问题:如何在spring和hibernate整合中,有个特殊需要,就是不用spring的AOP来切入事务,而是手动写事务。

           这个时候如果用getCurrentSession,就会报“Could not obtain transaction-synchronized Session for current thread”

2、最初的解决办法:

  加上这个配置

  <prop key="hibernate.current_session_context_class">thread</prop>

3、出现的问题:这段话只在hibernate的配置文件中有效,但在spring和hibernate的整合配置中就无效

4、为什么?

spring 整合hibernate管理事务后,由Spring的TransactionManager管理事务后, currentSession是绑定到SpringSessionContext的,而不是thread。

此时hibernate.current_session_context_class应该是SpringSessionContext,而它又会在使用LocalSessionFactoryBean时自动的设置。

所以就不需要你去设置current_session_context_class

5、最终解决办法:不要用getCurrentSession,用openSession。

原文地址:https://www.cnblogs.com/wwssgg/p/14434044.html