SSM在Controller中添加事务管理
本人使用:
- 集成开发环境:idea
- 项目管理工具:maven
- 数据库:oracle
- 框架:Spring+SpringMVC+myBatis
一般而言,事务都是加在Service层的,但也可以加在Controller层。。
看了不少人的博客,总结出两个方法:
- 在controller层写编程式事务
- 将事务配置定义在Spring MVC的应用上下文(spring-mvc.xml)中
现在具体来说说怎么实现的:
1.在controller层写编程式事务【繁琐,不推荐】
spring-mybatis.xml中事物管理器的配置依旧
1
2
3
4
5
6
7
8
9
|
<!-- 配置数据源事务 --> < bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" > < property name = "dataSource" ref = "dataSource" /> </ bean > <!-- 注解方式配置事务 @Transactional 但因为是在controller中写编程式事务,这里可以不配置<tx:annotation-driven transaction-manager="transactionManager" /> --> < tx:annotation-driven transaction-manager = "transactionManager" /> |
在controller中的方法里编写事务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//在每个controller中注入transactionManager @Resource private PlatformTransactionManager transactionManager; @PostMapping (value = "setCode" ) @ResponseBody public void setCode(Invoice invoice, InvoiceAddress invoiceAddress,String token,String orderIDs, Integer pid,HttpServletResponse response){ DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition(); defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition); try { invoiceService.insert(token,pid,invoice); int iID= invoice.getId(); String substring = orderIDs.substring( 0 , orderIDs.length()- 1 ); String[] split = substring.split( "," ); for (String string2 : split) { bOrderService.updateIStatus( "1" ,string2); } invoiceOrderService.insert(iID,substring); if (Integer.parseInt(invoice.getiType())== 1 ){ invoiceAddressService.insert(iID,invoiceAddress); } System.out.println( "======制造一个运行时异常aa======" ); System.out.println( "运行时异常:" + 100 / 0 ); //没有异常便手动提交事务 transactionManager.commit(status); printJson(response,result( 200 , "ok" )); } catch (Exception e){ //有异常便回滚事务 transactionManager.rollback(status); e.printStackTrace(); printJson(response,result( 500 , "false" )); } } |
2.将事务配置定义在Spring MVC的应用上下文(spring-mvc.xml)中【简单明了、一劳永逸】
spring-mybatis.xml中事物管理器配置不变
在spring-mvc.xml中也定义事务配置:
1
2
3
4
5
6
7
|
<!-- 命名空间中 加入: xmlns:tx="http://www.springframework.org/schema/tx" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd --> < tx:annotation-driven /> |
将@Transactional(rollbackFor = { Exception.class })注解打在Controller上
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
@Controller @RequestMapping (value = "/invoiceC" ) @Transactional (rollbackFor = { Exception. class }) public class InvoiceController extends BaseController { @Autowired private InvoiceService invoiceService; @Autowired private InvoiceOrderService invoiceOrderService; @Autowired private InvoiceAddressService invoiceAddressService; @Autowired private BalanceRechangeOrderService bOrderService; @PostMapping (value = "setCode" ) @ResponseBody public void setCode(Invoice invoice, InvoiceAddress invoiceAddress,String token,String orderIDs, Integer pid,HttpServletResponse response){ invoiceService.insert(token,pid,invoice); int iID= invoice.getId(); String substring = orderIDs.substring( 0 , orderIDs.length()- 1 ); //截取最后一个 String[] split = substring.split( "," ); //以逗号分割 for (String string2 : split) { bOrderService.updateIStatus( "1" ,string2); } invoiceOrderService.insert(iID,substring); if (Integer.parseInt(invoice.getiType())== 1 ){ //纸质发票,收货地址 invoiceAddressService.insert(iID,invoiceAddress); } System.out.println( "======制造一个运行时异常aa======" ); System.out.println( "运行时异常:" + 100 / 0 ); printJson(response,result( 200 , "ok" )); } } |
现在,我们来谈谈为什么之前??==》
- 在spring-mybatis.xml的<aop:config>添加对Controller的声明式事务拦截
- 在Controller的class加上@Transactional
两者均未生效呢???
原理:因为spring容器和spring-mvc是父子容器。在服务器启动时,会先加载web.xml配置文件 ==> 再加载spring配置文件 ==> 再回到web.xml【加载监听器;加载过滤器;加载前端控制器】==>再加载springMVC配置文件
在Spring配置文件中,我们扫描注册的是service实现类,就算扫描注册了controller 也会在后面加载SpringMVC配置文件[扫描注册controller]覆盖掉,所以想要在controller中实现事务管理,仅在spring配置文件配置<tx:annotation-driven>或<aop:config>是没有效果的,必须将事务配置定义在Spring MVC的应用上下文(spring-mvc.xml)中。
因为在spring-framework-reference.pdf文档中说明了:
<tx:annoation-driven/>只会查找和它在相同的应用上下文件中定义的bean上面的@Transactional注解
SSM下Controller层的事务配置问题
在写项目过程中遇到了多表联合修改数据时的事务问题,按照之前的学习,事务都是配置在service层中的,但是我的项目模块里一个service对应一个数据表,所以想在controller层加一个针对多个表的数据修改以及添加的事务配置。悲惨的是,在controller层配置事务出错没有回滚!
按照我已所接触的逻辑,控制层是不建议写业务逻辑的,所以在里面调用的是多个service层的接口(使用Autowired)来调用多个表的业务操作。但是多个表形成一个事务,所以我没找在service层里单独添加事务的合适的方法。如果有前辈想到合适的方法,望赐教!叩谢!
解决
原来的配置
首先是在service层上添加事务的配置,我这里的事务处理采用的是注解的方式,所以配置文件相较于配置事务的方式大大简化了。
首先命名空间中加入:
1
2
3
|
xmlns:tx="http://www.springframework.org/schema/tx" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd |
然后是xml文件的配置:
1
2
3
4
5
6
7
8
|
<!-- service除了业务(操作dao)还要有事务 --> < tx:annotation-driven transaction-manager = "txManager" /> <!-- 配置Spring的声明式事务管理器 --> < bean id = "txManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" > < property name = "dataSource" ref = "dataSource" ></ property > </ bean > |
其中,数据源我是配置在了dao层的配置文件中,由于都在spring的管理之下,所以在service直接使用是能够找到的。
以下是我的maven依赖的jar包版本:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-tx</ artifactId > < version >5.1.5.RELEASE</ version > </ dependency > <!-- Spring jdbc事务管理 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-jdbc</ artifactId > < version >5.1.5.RELEASE</ version > </ dependency > |
以上是我起初的配置。但是仅仅这样是无法在controller层添加事务的。
修正后的配置
在service层的配置文件不变的情况下,我们想要在controller层添加事务,只需要在spring-mvc.xml中引入事务的注解驱动标签即可。
1
2
|
<!--在xml文件头部引入命名空间,参考serviice层--> < tx:annotation-driven /> |
为什么会这样?
首先我们来看配置文件的加载:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<!-- 配置前端控制器 --> < servlet > < servlet-name >DispatcherServlet</ servlet-name > < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class > < init-param > < param-name >contextConfigLocation</ param-name > < param-value >classpath:spring-mvc.xml</ param-value > </ init-param > </ servlet > < servlet-mapping > < servlet-name >DispatcherServlet</ servlet-name > < url-pattern >*.action</ url-pattern > </ servlet-mapping > <!-- 配置spring容器加载的监听器 --> < listener > < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class > </ listener > < context-param > < param-name >contextConfigLocation</ param-name > < param-value >classpath:spring-*.xml</ param-value > </ context-param > |
以上是我的web.xml的部分配置。在项目启动过程中,加载spring-mvc.xml是使用DispatcherServlet加载的,而加载spring-service.xml与spring-dao.xml使用的是ContextLoaderListener。
然后我们需要知道的是,ContextLoaderListener是早于DispatcherServlet启动的,而在ContextLoaderListener加载service层配置时controller并没有加载到容器中,但是此时事务的动态代理已经切入到了service层,所以后续的controller层并没有被增强。
因此,我们需要在controller层再次加入 <tx:annotation-driven/>。
仅为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_40594137/article/details/82772545