本人使用:
- 集成开发环境:idea
- 项目管理工具:maven
- 数据库:oracle
- 框架:Spring+SpringMVC+myBatis
一般而言,事务都是加在Service层的,但也可以加在Controller层。。
看了不少人的博客,总结出两个方法:
- 在controller层写编程式事务
- 将事务配置定义在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"));
}
}
现在,我们来谈谈为什么之前??==》
- 在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注解