這個問題出現在整合springmvc+spring4+hibernate5的時候出現的。首先事務要配好,我是這樣配置的:
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
//之后在合適的位置添加注解(一般在實現類或方法上):@Transactional
//添加事務也可以解決這個異常:Could not obtain transaction-synchronized Session for current thread
但是設置了之后事務好像沒生效,在查看spring官方文檔中說了這么一句:
就說如果你在springmvc中配置了<tx:annotation-driven/>
,那么spring中的
<tx:annotation-driven transaction-manager="txManager"/>
就失效了,他不會掃描除了controller以外的包中的有@Transactional
注解的地方。
所以解決方法就是分段掃描:
SpringMVC.xml配置文件--> 只掃描controller組件 注意使用 use-default-filters="false"
<context:component-scan base-package="com.yx.*" use-default-filters="false" >
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
ApplicationContext.xml配置文件-->掃描除controller外的所有組件
<context:component-scan base-package="com.yx.*" >
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
上面方法是:這位仁兄 提供的。
在此之前我看過其他解決方法,如:
@Transactional
所導的包是:org.springframework.transaction.annotation.Transactional
更多解決方法看下面: