美文网首页
注解式事务解决方案

注解式事务解决方案

作者: alpacino_1010 | 来源:发表于2019-05-26 20:39 被阅读0次

事务异常测试

2.jpg

在插入商品表后,人为制造一个异常。我们运行程序,新增商品数据,观察运行结果。
通过观察发现,程序发生异常 ,商品表仍然会存储记录(虽然显示增加失败,但依然会存入数据库中),这是不符合我们要求的。
这是因为我们目前的系统还没有配置事务。

配置文件,service 工程的 spring 目录下创建 applicationContext-tx.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 事务管理器  -->  
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
    <property name="dataSource" ref="dataSource" />  
</bean>  
  
<!-- 开启事务控制的注解支持 -->  
<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

在方法或类上添加注解

1.jpg

经过测试发现,系统发生异常,商品表不会新增记录,事务配置成功。

相关文章

网友评论

      本文标题:注解式事务解决方案

      本文链接:https://www.haomeiwen.com/subject/kvgftctx.html