6.注解式事务配置 6.1 事务异常测试 我们修改 pinyougou-sellergoods-service 工程 GoodsServiceImpl.java 的 add 方法


/**
 
* 增加
*/ @Override

public  void  add(Goods  goods)  {
goods.getGoods().setAuditStatus("0"); goodsMapper.insert(goods.getGoods());  //插入商品表
 
int  x=1/0; goods.getGoodsDesc().setGoodsId(goods.getGoods().getId());
goodsDescMapper.insert(goods.getGoodsDesc());//插入商品扩展数据
 
saveItemList(goods);//插入商品 SKU 列表数据
 
}

在插入商品表后,人为制造一个异常。我们运行程序,新增商品数据,观察运行结果。

通过观察,我们发现,程序发生异常 ,商品表仍然会存储记录,这是不符合我们要求的。这是因为我们目前的系统还没有配置事务。

6.1 注解式事务解决方案 6.1.1 配置文件 在 pinyougou-sellergoods-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 [url=http://www.springframework.org/schema/beans/spring-beans.xsd]http://www.springframework.org/schema/beans/spring-beans.xsd[/url]
 
[url=http://www.springframework.org/schema/mvc]http://www.springframework.org/schema/mvc[/url]
[url=http://www.springframework.org/schema/mvc/spring-mvc.xsd]http://www.springframework.org/schema/mvc/spring-mvc.xsd[/url]
 
 
[url=http://www.springframework.org/schema/tx]http://www.springframework.org/schema/tx[/url] [url=http://www.springframework.org/schema/tx/spring-tx.xsd]http://www.springframework.org/schema/tx/spring-tx.xsd[/url]
 
[url=http://www.springframework.org/schema/context]http://www.springframework.org/schema/context[/url] [url=http://www.springframework.org/schema/context/spring-context.xsd]http://www.springframework.org/schema/context/spring-context.xsd[/url]">
<!-- 事务管理器 -->
 
<bean  id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 
<property  name="dataSource"  ref="dataSource"  />
 
 
</bean>
 
<!-- 开启事务控制的注解支持 -->
 
<tx:annotation-driven  transaction-manager="transactionManager"/>
 
 
</beans>

6.1.1 在方法上添加注解

/**
 
*服务实现层
 
*@author  Administrator
 
*
 
*/ @Service
@Transactional
 
public  class  GoodsServiceImpl  implements  GoodsService{
 
........
 
}

经过测试,我们发现,系统发生异常,商品表不会新增记录,事务配置成功。 删除掉测试代码 int x=1/0 我们需要将所有涉及多表操作的服务类添加事务注解,例如 SpecificationServiceImpl 类