spring + mybatis 注解式事务不回滚的原因分析 @Transactional
在一个项目中发现spring的事务无法回滚。
DEBUG: org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49f9ce55] was not registered for synchronization because synchronization is not active DEBUG: org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [ConnectionHandle{url=jdbc:postgresql://localhost/mypro, user=mypro, debugHandle=null, lastResetAgoInSec=92, lastUsedAgoInSec=92, creationTimeAgoInSec=92}] will not be managed by Spring
在网上找了好多,都没解决
我搜到的资料相关链接有:
http://www.cnblogs.com/xunux/p/4388124.html
http://www.iteye.com/topic/1123069
http://hwak.iteye.com/blog/1611970
http://blog.csdn.net/will_awoke/article/details/12002705 (最终在这里得到启发,问题解决)
其实,上面几个链接,都提到是包扫描的问题,要在包扫描的配置里加上
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
没错,真的是这个问题引起的。
起初,我已经加上了,但问题依旧,问题研究出在哪里呢?????:( :( :((伤心啊!!!)
后来找到这里:http://blog.csdn.net/will_awoke/article/details/12002705,里面有讲到:
Spring容器优先加载由ServletContextListener(对应applicationContext.xml)产生的父容器,而SpringMVC(对应mvc_dispatcher_servlet.xml)产生的是子容器。子容器Controller进行扫描装配时装配的@Service注解的实例是没有经过事务加强处理,即没有事务处理能力的Service,而父容器进行初始化的Service是保证事务的增强处理能力的。如果不在子容器中将Service exclude掉,此时得到的将是原样的无事务处理能力的Service,因为在多上下文的情况下,如果同一个bean被定义两次,后面一个优先。
好了,问题关键是父容器和子容器的事了。
个人心得:就是父容器加载后,又重新加载了子容器,使得SqlSession不同步,后来的子容器中的SqlSession没有spring的事务支持所以gg
在spring-mvc.xml中加:
<!-- 开启包扫描 --> <context:component-scan base-package="com.oneclouder.pidm"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>在applicationContext.xml中加
<!-- 开启包扫描 --> <context:component-scan base-package="com.oneclouder.pidm"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>