spring事务的实现(三):spring基于注解的事务管理
spring基于注解的事务管理步骤(以转账为例):
第一步:业务层的哪些方法需要事务
package com.cc.service;
public interface IUserInfoService {
/*
* from:转出的账户 to:转入的账户 money:转的金额
*
*/
public void zz(int from, int to, int money) throws Exception;
}
第二步:开启注解配置,同时启用注解事务
<!-- 1. 开启注解配置 扫描com.cc中的哪些包使用了配置-->
<context:annotation-config/>
<context:component-scan base-package="com.cc" ></context:component-scan>
<!-- 2、注解事务 启用注解事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
第三步:使用@Transactional标示需要事务的方法
package com.cc.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.cc.mapper.UserInfoMapper;
import com.cc.model.UserInfo;
import com.cc.service.IUserInfoService;
//业务层
@Component
public class UserInfoServiceImpl3 implements IUserInfoService {
@Autowired
private UserInfoMapper userInfoMapper;
// @Autowired
// public UserInfoServiceImpl1(PlatformTransactionManager transactionManager) {
// this.transactionTemplate = new TransactionTemplate(transactionManager);
// }
/**
* 转账业务:旺财(from)转账给来福(to),转money钱
*
* 旺财(from) 更新操作 减money 来福 (to) 更新操作 加money money =200
*
*
* zz(1,2,300)
*/
@Override
// @Transactional(readOnly=true)
@Transactional//开启事务注解
public void zz(int from, int to, int money) throws Exception {
// 转账的操作
zzOptional(from, to, money);
}
private void zzOptional(int from, int to, int money) throws Exception {
// 一,==============旺财的钱减少300==============
// 1.1查询旺财有多少钱
UserInfo wc = userInfoMapper.selectByPrimaryKey(from);
System.out.println(wc);
// 1.2扣旺财有300
wc.setMoney(wc.getMoney() - money);
int result = userInfoMapper.updateByPrimaryKey(wc);
// ==============二,来福的钱增加300==============
// 1.1查询旺财有多少钱
UserInfo lf = userInfoMapper.selectByPrimaryKey(to);
System.out.println(lf);
// 1.2扣旺财有300
lf.setMoney(lf.getMoney() + money);
int result2 = userInfoMapper.updateByPrimaryKey(lf);
// ==============最后的结果==============
if (result > 0 && result2 > 0) {
System.out.println("转账成功!!");
} else {
// int a = 10/0;//产生一个异常
throw new Exception("转账失败");// 产生一个异常
}
}
}
第四步:编写单元测试方法
package com.cc.proxy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.cc.service.IUserInfoService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-datasource-annotation.xml")
public class SpringAnnotationTrasactionTest {
// 注解事务-基于注解的业务层类
@Autowired
@Qualifier("userInfoServiceImpl3")
private IUserInfoService iUserInfoService;
@Test
public void whenZz2Success() {
try {
iUserInfoService.zz(1, 2, 100);
} catch (Exception e) {
System.out.println("转账失败,回滚");
System.out.println(e.getMessage());
}
}
}