八、转账案例中对事务的控制

一、转账失败案例

bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置Service -->
    <bean id="accountService" class="com.liaoxiang.service.impl.AccountServiceImpl">
        <!-- 注入dao,set方法注入 -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.liaoxiang.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner,set方法注入 -->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源,构造函数注入-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

IAccountDao

public interface IAccountDao {
    void updateAccount(Account account);
    Account findAccountByName(String accountName);
}

AccountDaoImpl

public class AccountDaoImpl implements IAccountDao {
    private QueryRunner runner;
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountByName(String accountName) {
        try{
            List<Account> accounts = runner.query("select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);
            if(accounts == null || accounts.size() == 0){
                return null;
            }
            if(accounts.size() > 1){
                throw new RuntimeException("结果集不唯一,数据有问题");
            }
            return accounts.get(0);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

IAccountService

public interface IAccountService {
    void updateAccount(Account account);
    /**
     * 转账功能
     * @param sourceName    转出账户名称
     * @param targetName    转入账户名称
     * @param money         转账金额
     */
    void transfer(String sourceName,String targetName,Float money);
}

AccountServiceImpl

public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    /**
     * @param sourceName        转出账户名称
     * @param targetName        转入账户名称
     * @param money             转账金额
     *  为了防止异常前面方法的执行成功,异常后面的没有执行,下面操作数据库的方法应该只公用一个connection对象
     *  即: 一起成功,一起失败
     *  需要使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只有一个能控制事务的对象
     */
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //1、根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        //2、根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        //3、转出账户减钱
        source.setMoney(source.getMoney()-money);
        //4、转入账户加钱
        target.setMoney(target.getMoney()+money);
        //5、更新转出账户
        accountDao.updateAccount(source);
        //6、更新转入账户
        accountDao.updateAccount(target);
    }
}

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    private IAccountService accountService;
    @Test
    public  void testTransfer(){
        accountService.transfer("aaa","bbb",100f);
    }
}

成功转账:
完成转账
制造异常:int i=1/0;

public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    /**
     * @param sourceName        转出账户名称
     * @param targetName        转入账户名称
     * @param money             转账金额
     *  为了防止异常前面方法的执行成功,异常后面的没有执行,下面操作数据库的方法应该只公用一个connection对象
     *  即: 一起成功,一起失败
     *  需要使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只有一个能控制事务的对象
     */
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //1、根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        //2、根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        //3、转出账户减钱
        source.setMoney(source.getMoney()-money);
        //4、转入账户加钱
        target.setMoney(target.getMoney()+money);
        //5、更新转出账户
        accountDao.updateAccount(source);
        // 制造异常
        int i=1/0;
        //6、更新转入账户
        accountDao.updateAccount(target);
    }
}

运行出现异常:
在这里插入图片描述
事物并没有得到控制
在这里插入图片描述

原因分析:

在bean.xml中配置的QueryRunner对象是多例的,每次要操作数据库时,都会从数据源获取新的连接,每个连接都有自己的事物,在转账中异常代码之前的连接都能成功提交事务,异常代码之后的则不能,要使同时提交或者同时回滚,要求执行转账任务线程上只有一个连接。

解决办法:

使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只有一个能控制事物的对象。

二、改进上面的案例是能够控制事物

项目结构
在这里插入图片描述
utils工具类:

package com.liaoxiang.utils;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @auther Mr.Liao
 * 连接数据库的工具类,从数据源中获取一个链接,并且实现和线程的绑定
 */
public class ConnectionUtils {
    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    /**
     * 获取当前线程上的连接
     * @return
     */
    public Connection getThreadConnection() {
        try{
            //1.先从ThreadLocal上获取
            Connection conn = tl.get();
            //2.判断当前线程上是否有连接
            if (conn == null) {
                //3.从数据源中获取一个连接,并且存入ThreadLocal中
                conn = dataSource.getConnection();
                tl.set(conn);
            }
            //4.返回当前线程上的连接
            return conn;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    /**
     * 把连接和线程解绑
     */
    public void removeConnection(){
        tl.remove();
    }
}
package com.liaoxiang.utils;

/**
 * @auther Mr.Liao
 * @date 2019/4/15 9:50
 *
 * 事物管理相关的工具类:Advice(通知/增强)
 */
public class TransactionManager {
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 释放连接
     */
    public void release(){
        try {
            connectionUtils.getThreadConnection().close();//还回连接池中
            connectionUtils.removeConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

修改bean配置文件

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

    <!-- 配置Service -->
    <bean id="accountService" class="com.liaoxiang.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
        <!--注入事物管理器-->
        <property name="txManager" ref="txManager"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.liaoxiang.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
        <!-- 注入ConnectionUtils -->
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 配置Connection的工具类 ConnectionUtils -->
    <bean id="connectionUtils" class="com.liaoxiang.utils.ConnectionUtils">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置事务管理器-->
    <bean id="txManager" class="com.liaoxiang.utils.TransactionManager">
        <!-- 注入ConnectionUtils -->
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
</beans>

修改AccountDaoImpl

package com.liaoxiang.dao.impl;

import com.liaoxiang.dao.IAccountDao;
import com.liaoxiang.domain.Account;
import com.liaoxiang.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * @auther Mr.Liao
 * @date 2019/4/15 9:48
 */
public class AccountDaoImpl implements IAccountDao {
    private QueryRunner runner;
    private ConnectionUtils connectionUtils;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    public void updateAccount(Account account) {
        try{
            runner.update(connectionUtils.getThreadConnection(),
                    "update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public Account findAccountByName(String accountName) {
        try{
            List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),
                    "select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);
            if(accounts == null || accounts.size() == 0){
                return null;
            }
            if(accounts.size() > 1){
                throw new RuntimeException("结果集不唯一,数据有问题");
            }
            return accounts.get(0);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

修改AccountServiceImpl

package com.liaoxiang.service.impl;

import com.liaoxiang.dao.IAccountDao;
import com.liaoxiang.domain.Account;
import com.liaoxiang.service.IAccountService;
import com.liaoxiang.utils.TransactionManager;

import java.util.List;

/**
 * @auther Mr.Liao
 * @date 2019/4/15 9:54
 */
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;
    private TransactionManager txManager;
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }
    public void updateAccount(Account account) {
        try {
            //1、开启事物
            txManager.beginTransaction();
            //2、执行操作
            accountDao.updateAccount(account);
            //3、提交事务
            txManager.commit();
        } catch (Exception e) {
            //4、回滚事物
            txManager.rollback();
            e.printStackTrace();
        } finally {
            //5、释放链接
            txManager.release();
        }
    }
    /**
     * @param sourceName        转出账户名称
     * @param targetName        转入账户名称
     * @param money             转账金额
     *  为了防止异常前面方法的执行成功,异常后面的没有执行,下面操作数据库的方法应该只公用一个connection对象
     *  需要使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只有一个能控制事务的对象
     */
    public void transfer(String sourceName, String targetName, Float money) {
        try {
            //1、开启事物
            txManager.beginTransaction();
            //2、执行操作
            //2.1 根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            //2.2 根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            //2.3 转出账户减钱
            source.setMoney(source.getMoney()-money);
            //2.4 转入账户加钱
            target.setMoney(target.getMoney()+money);
            //2.5 更新转出账户
            accountDao.updateAccount(source);
            // 制造异常
            int i=1/0;
            //2.6更新转入账户
            accountDao.updateAccount(target);
            //3、提交事务
            txManager.commit();
        } catch (Exception e) {
            //4、回滚事物
            txManager.rollback();
            System.out.println(e.getMessage());
        } finally {
            //5、释放链接
            txManager.release();
        }
    }
}

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    private IAccountService accountService;
    @Test
    public  void testTransfer(){
        accountService.transfer("aaa","bbb",100f);
    }
}

在这里插入图片描述
在这里插入图片描述
以上达到了对事物的控制

总结:

虽然达到了对事物的控制,但是各种配置显得很麻烦,而且在AccountServiceImpl中的代码变得异常的臃肿,每执行一次数据库操作都要进行事务相关的方法,解决办法就是动态代理,更多内容请参见下一节!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值