一个小故事:小明今天给朋友赚钱呢,已经提交了,但是手机出问题了,导致自己的钱已经转出去了,但是小明的朋友没收到,这个是为什么呢?
我们首先来写写这个代码:
首先我们来写配置文件:applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.liurui"></context:component-scan>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg type="javax.sql.DataSource" ref="dataSource"></constructor-arg>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<contex
2,我们来看下业务层的接口代码:
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Autowired
private TransactionManager transactionManager;
//假设事务需要处理
public void update(Account account){
try {
//开启事务
transactionManager.beginTransation();
//提交事务
accountDao.update(account);
transactionManager.commit();
}catch (Exception e){
//回滚事务
transactionManager.rollBack();
e.printStackTrace();
}finally {
//关闭事务
transactionManager.release();
}
}
public void stranfer(String fromName, String toName, Float money) {
try {
//开启事务
transactionManager.beginTransation();
//获取转出账户的名称
Account fromAccount = accountDao.findByName(fromName);
//获取转入账户的名称
Account toAccount = accountDao.findByName(toName);
//判断转出账户的总金额是否大于要转出的钱
if(fromAccount.getMoney()>=money){
//大于
//执行转出账户的金额减少
fromAccount.setMoney(fromAccount.getMoney()-money);
//执行转入账户的金额增加
toAccount.setMoney(toAccount.getMoney()+money);
//更新转出账户的信息
accountDao.update(fromAccount);
//更新转入账户的信息
accountDao.update(toAccount);
}else{
System.out.println("钱不足!");
//事务的回滚
transactionManager.rollBack();
}
//事务的提交
transactionManager.commit();
}catch (Exception e){
//事务的回滚
transactionManager.rollBack();
e.printStackTrace();
}finally {
//事务的释放
transactionManager.release();
}
}
}
3,我们来分析下:
从这张图上我们可以看出每执行一个方法其实就是创建一个connection连接,那么我们就需要用到事务的控制,让他们在同一个线程下执行