@Transactional注解不回滚缘由详解

最近试了试spring的回滚功能,根据网上的教程配置怎么都很差使,遂寻找答案,html

网上的答案都是这么讲的:mysql

1. 检查你方法是否是public的。spring

2. 你的异常类型是否是unchecked异常。
若是我想check异常也想回滚怎么办,注解上面写明异常类型便可。sql

@Transactional(rollbackFor=Exception.class)

相似的还有norollbackFor,自定义不回滚的异常。数据库

3. 数据库引擎要支持事务,若是是mysql,注意表要使用支持事务的引擎,好比innodb,若是是myisam,事务是不起做用的。express

4. 是否开启了对注解的解析mvc

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

5. spring是否扫描到你这个包,以下是扫描到org.test下面的包app

<context:component-scan base-package="org.test" ></context:component-scan>

我都检查了,但就是不回滚,再找,终于发现了问题在哪儿..net

通常咱们在Spring的配置文件application.xml中对Service层代码配置事务管理,能够对Service的方法进行AOP加强或事务处理如事务回滚,可是遇到一个问题,在Controller类中调用Service层方法,配置的事务管理会失效,查询相关资料发现缘由。其实Spring和SpringMVC俩个容器为父子关系,Spring为父容器,而SpringMVC为子容器。也就是说application.xml中应该负责扫描除@Controller的注解如@Service,而SpringMVC的配置文件应该只负责扫描@Controller,不然会产生重复扫描致使Spring容器中配置的事务失效。code

最主要的是springmvc的配置文件,不能配置重复扫描Service,

能够这样配置

<context:component-scan base-package="com.zj.module.batis.controller"/>,

也能够

<context:component-scan base-package="com.zj.module.batis">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>

直接过滤掉Service.

 

两位博主的连接:

1.https://www.cnblogs.com/wuxiaofeng/p/6819209.html

2.https://blog.csdn.net/qq_32588349/article/details/52097943

相关文章
相关标签/搜索