【Spring】Spring中的事务

service层的实现类主要代码:

    public void transfer(String sourceName, String targetName, Double money) {
        //根据名称查询转出账户
        Account sourceAccount = accountDao.findAccountByName(sourceName);
        //根据名称查询转入账户
        Account targetAccount = accountDao.findAccountByName(targetName);
        //转出账户减额
        sourceAccount.setMoney(sourceAccount.getMoney()-money);
        //转入账户增额
        targetAccount.setMoney(targetAccount.getMoney()+money);
        //更新账户
        accountDao.updateAccount(sourceAccount);
        accountDao.updateAccount(targetAccount);
    }

Dao层实现类主要代码:

    public Account findAccountByName(String accountName) {
        try {
            List<Account> accounts = runner.query("select * from account1 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 (SQLException e) {
            throw new RuntimeException(e);
        }
    }

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

进行测试:

    public void testTransfer(){
        as.transfer("aaa","bbb",100.0);
    }

代码可以成功运行,但是如果在service中添加一个异常:

    public void transfer(String sourceName, String targetName, Double money) {
        //根据名称查询转出账户
        Account sourceAccount = accountDao.findAccountByName(sourceName);
        //根据名称查询转入账户
        Account targetAccount = accountDao.findAccountByName(targetName);
        //转出账户减额
        sourceAccount.setMoney(sourceAccount.getMoney()-money);
        //转入账户增额
        targetAccount.setMoney(targetAccount.getMoney()+money);
        //更新账户
        accountDao.updateAccount(sourceAccount);
        //这里出现异常
        int i = 1/0;
        accountDao.updateAccount(targetAccount);
    }

此时转出账户扣除100元,但是转入账户的钱并没有增加。这是因为上面的几条命令都各自获取一个连接,每个连接都有一个自己的独立事务。

解决问题的思路上只建立一个connection,只有一个事务,只要有一个操作失败就会进行回滚。

需要使用TreadLocal对象把Connection和当前的线程进行绑定,从而使一个线程中只有一个能控制事务的对象。

改造

新建一个连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定和解绑:

/**
 * @author liwenlong
 * @data 2020/5/16
 */
public class ConnectionUtils {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    //获取当前线程的连接
    public Connection getThreadConnection(){
        //先从ThreadLocal上获取
        Connection connection = tl.get();
        //判断当前线程上是否有连接
        if(connection == null){
            //从数据源中获取一个连接,并且存入到ThreadLocal当中
            try {
                connection = dataSource.getConnection();
                tl.set(connection);

            } catch (Exception e) {
                new RuntimeException(e);
            }
        }
        //返回当前线程上的连接
        return connection;
    }
    //解绑
    public void removeConnection(){
        tl.remove();
    }

}

创建事务管理相关的工具类:


/**
 * 和事务管理相关的公路类,它包含了开启事务,提交事务,管理事务
 * @author liwenlong
 * @data 2020/5/17
 */
public class TransactionManager {
    //获取一个连接
    private ConnectionUtils connectionUtils;

    //添加set方法来提供依赖注入
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    //开启事务
    public void beginTransaction(){
        //关闭自动提交事务(默认也是关闭)
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //提交事务
    public void commit(){
        //关闭自动提交事务(默认也是关闭)
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //回滚事务
    public void rollback(){
        //关闭自动提交事务(默认也是关闭)
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //释放连接
    public void release(){
        //关闭自动提交事务(默认也是关闭)
        try {
            //将线程还到线程池
            connectionUtils.getThreadConnection().close();
            //连接和线程解绑
            connectionUtils.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

重新Dao接口类,改为从ConnectionUtils中获取连接,而不是从数据源当中:

/**
 * @author liwenlong
 * @data 2020/5/13
 */
public class AccountDaoImpl implements IAccountDao {
    private QueryRunner runner; //核心对象
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

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

    public List<Account> findAllAccount() {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account1", new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer id) {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account1 where id = ?",new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void insertAccount(Account account) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"insert into account1(name,money)values(?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

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

    public void deleteAccount(Integer id) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"delete from account1 where id = ?",id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountByName(String accountName) {
        try {
            List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account1 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 (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

重写Service的实现类:

public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

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

    public List<Account> findAllAccount() {
        try {
            //开启事务
            transactionManager.beginTransaction();
            //执行任务
            List<Account> accounts = accountDao.findAllAccount();
            //提交事务
            transactionManager.commit();
            //返回结果
            return accounts;
        } catch (Exception e) {
            //回滚操作
            transactionManager.rollback();
            throw new RuntimeException(e);
        } finally {
            //释放连接
            transactionManager.release();
        }
    }

    public Account findAccountById(Integer id) {
        try {
            //开启事务
            transactionManager.beginTransaction();
            //执行任务
            Account account = accountDao.findAccountById(id);
            //提交事务
            transactionManager.commit();
            //返回结果
            return account;
        } catch (Exception e) {
            //回滚操作
            transactionManager.rollback();
            throw new RuntimeException(e);
        } finally {
            //释放连接
            transactionManager.release();
        }
    }

    public void insertAccount(Account account) {
        try {
            //开启事务
            transactionManager.beginTransaction();
            //执行任务
            accountDao.insertAccount(account);
            //提交事务
            transactionManager.commit();
        } catch (Exception e) {
            //回滚操作
            transactionManager.rollback();
            throw new RuntimeException(e);
        } finally {
            //释放连接
            transactionManager.release();
        }
    }

    public void updateAccount(Account account) {
        try {
            //开启事务
            transactionManager.beginTransaction();
            //执行任务
            accountDao.updateAccount(account);
            //提交事务
            transactionManager.commit();
        } catch (Exception e) {
            //回滚操作
            transactionManager.rollback();
            throw new RuntimeException(e);
        } finally {
            //释放连接
            transactionManager.release();
        }
    }

    public void deleteAccount(Integer id) {
        try {
            //开启事务
            transactionManager.beginTransaction();
            //执行任务
            accountDao.deleteAccount(id);
            //提交事务
            transactionManager.commit();
        } catch (Exception e) {
            //回滚操作
            transactionManager.rollback();
            throw new RuntimeException(e);
        } finally {
            //释放连接
            transactionManager.release();
        }
    }

    public void transfer(String sourceName, String targetName, Double money) {
        try {
            //开启事务
            transactionManager.beginTransaction();

            //执行任务

            //根据名称查询转出账户
            Account sourceAccount = accountDao.findAccountByName(sourceName);
            //根据名称查询转入账户
            Account targetAccount = accountDao.findAccountByName(targetName);
            //转出账户减额
            sourceAccount.setMoney(sourceAccount.getMoney()-money);
            //转入账户增额
            targetAccount.setMoney(targetAccount.getMoney()+money);
            //更新账户
            accountDao.updateAccount(sourceAccount);
            accountDao.updateAccount(targetAccount);

            //提交事务
            transactionManager.commit();
        } catch (Exception e) {
            e.printStackTrace();
            //回滚操作
            transactionManager.rollback();
        } finally {
            //释放连接
            transactionManager.release();
        }
    }
}

根据以上内容,将需要进行依赖注入的对象通过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.lwl.service.impl.AccountServiceImpl">
        <!--注入Dao对象-->
        <property name="accountDao" ref="accountDao"></property>
        <!--注入connectionUtils-->
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.lwl.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/test"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1022"></property>
    </bean>

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

    <!--配置事务管理器-->
    <bean id="transactionManager" class="com.lwl.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
</beans>

此时事务控制成功,但是我们发现当前程序非常的臃肿。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章