項目已送出至Github
位址:https://github.com/ylw-github/pingyougou.git
版本:2646456bff33de6ccecb9a598b156fecef78abed
引出問題
編寫單元測試,新增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 清單資料
}
在插入商品表後,人為制造一個異常。我們運作程式,新增商品資料,觀察運作結果。
通過觀察,我們發現,程式發生異常 ,商品表仍然會存儲記錄,這是不符合我們要求的。這是因為我們目前的系統還沒有配置事務。
配置事務
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
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>
2.在方法上添加注解
/**
* 服務實作層
* @author Administrator
*
*/
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService{
........
}