SSM中 实现在Controller中添加事务管理

本人使用:

  • 集成开发环境:idea
  • 项目管理工具:maven
  • 数据库:oracle
  • 框架:Spring+SpringMVC+myBatis

一般而言,事务都是加在Service层的,但也可以加在Controller层。。                        

看了不少人的博客,总结出两个方法:

  1. 在controller层写编程式事务
  2. 将事务配置定义在Spring MVC的应用上下文(spring-mvc.xml)中

现在具体来说说怎么实现的:

1.在controller层写编程式事务【繁琐,不推荐】:

  1.spring-mybatis.xml中事物管理器的配置依旧

<!-- 配置数据源事务 -->
<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" />

  2.在controller中的方法里编写事务

//在每个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)中【简单明了、一劳永逸】

  1,spring-mybatis.xml中事物管理器配置不变

  2,在spring-mvc.xml中也定义事务配置:

<!--
    命名空间中 加入:
    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/>

  3,将 @Transactional(rollbackFor = { Exception.class })注解打在Controller上

@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"));

    }
}

现在,我们来谈谈为什么之前??==》

  1. 在spring-mybatis.xml的<aop:config>添加对Controller的声明式事务拦截
  2. 在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注解

 

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值