Spring深入学习(6)AOP导学:将事务管理转移到业务层

Account项目添加功能

在之前写过的基于xml配置文件的练习之上,添加一个转账的功能。
转账需要通过用户名查询用户对象。

    /**
     * 通过用户名查询用户对象
     * @param accountName
     * @return
     */
    public Account findAccountByName(String accountName) {
        try {
            return runner.query("select * from account where name = ?", new BeanHandler<Account>(Account.class),accountName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

添加转账的业务类

/**
     * 转账业务类
     * @param sourceName
     * @param targetName
     * @param money
     */
    public void transfer(String sourceName, String targetName, Float money) {

        Account sourceAccount = accountDao.findAccountByName(sourceName);

        Account targetAccount = accountDao.findAccountByName(targetName);

        Float sourceAfterMoney = sourceAccount.getMoney() - money;
        Float targetAfterMoney = targetAccount.getMoney() + money;

        sourceAccount.setMoney(sourceAfterMoney);
        targetAccount.setMoney(targetAfterMoney);

        accountDao.update(sourceAccount);
		//int a = 1/0;
        accountDao.update(targetAccount);

        System.out.println(sourceName + "向" + targetName +"转账" + money + "元成功");
    }

添加一个测试方法,测试功能

@Test
    public void  testTransfer() {

        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

        AccountService accountService = (AccountService) ac.getBean("accountService");

        accountService.transfer("TQ","YY",100f);

    }

发现,功能可以正常运行。数据库中的数据也满足了一致性。
但是现在依然存在一个问题。
我们的数据库连接对象是多实例的,也就是说每一次读取或写入数据库都是一个独立的事务。现在我们放开转账方法中可以导致算数异常的注释。
再次运行
发现,转出账户的金额少了100,但是转入账户的金额并没有相应的增加。
这时候我就需要我们将每个方法中的事务的提交合并为同一个事务。

对转账业务进行优化

事务不统一的原因就是,数据源的连接时多实例的。所以我们需要将每个业务方法的数据源连接合并为一个连接。
使用ThreadLocal方法将Connection与当前线程进行绑定,业务方法的链接都从连接工具类中获取。
由于在web开发环境中,我们会使用到线程池,当结束一个线程时并非真正的结束了一个线程,而是将线程操作权还回了线程池,但此时线程上还绑定这一个连接对象,所以要添加一个解绑的方法

package com.tianqicode.utils;

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

/**
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
 */
public class ConnectionUtil {

    private DataSource source;

    public void setSource(DataSource source) {
        this.source = source;
    }

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


    /**
     * 获取当前线程上的连接
     * @return
     */
    public Connection getThreadLoacal() {

            try {

                //1、先从当前线程获取连接
                Connection connection = tl.get();
                //判断当前线程是否有连接
                if (connection == null) {
                    //3、如果当前线程没有连接,则从数据源获取一个连接
                    connection = source.getConnection();
                    //4、将连接存入线程
                    tl.set(connection);
                }
                    //返回当前线程的连接
                return connection;

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
    }
    /**
     * 把连接与线程解绑
     */
    public void removeConnection() {
        tl.remove();
    }
}

创建事务控制工具类,将自动提交事务变为手动控制事务

package com.tianqicode.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
 */
public class TransactionManager {

    private ConnectionUtil connectionUtil;

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }

    /**
     * 开启事务
     */
    public void beginTransaction() {

        try {
            //自动提交事务关闭
            connectionUtil.getThreadLoacal().setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commitTransaction() {

        try {
            connectionUtil.getThreadLoacal().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollbackTransaction() {
        try {
            connectionUtil.getThreadLoacal().rollback();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 断开连接
     */
    public void release() {

        try {
            //并非断开连接,而是将连接还回连接池中
            connectionUtil.getThreadLoacal().close();
            connectionUtil.removeConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

修改业务方法,将事务操作放在业务层

package com.tianqicode.service.Impl;

import com.tianqicode.dao.AccountDao;
import com.tianqicode.domain.Account;
import com.tianqicode.service.AccountService;
import com.tianqicode.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {

    //这里调用Dao持久层的对象
    //@Autowired
    private AccountDao accountDao;

    private TransactionManager transactionManager;

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

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


    public List<Account> findAllAccount() {

        try {
            //1、开启事务
            transactionManager.beginTransaction();
            //2、执行操作
            List<Account> accounts = accountDao.findAllAccount();
            //3、提交事务
            transactionManager.commitTransaction();
            //4、返回结果
            return accounts;
        } catch (Exception e) {
            //5、回滚操作
            transactionManager.rollbackTransaction();
            throw new RuntimeException(e);
        } finally {
            //6、释放连接
            transactionManager.release();
        }
    }

    public Account findAccountById(Integer accountId) {

        try {
            //1、开启事务
            transactionManager.beginTransaction();
            //2、执行操作
            Account account = accountDao.findAccountById(accountId);
            //3、提交事务
            transactionManager.commitTransaction();
            //4、返回结果
            return account;

        }catch (Exception e){
            //5、回滚操作
            transactionManager.rollbackTransaction();
            throw new RuntimeException(e);
        }finally {
            //6、释放连接
            transactionManager.release();
        }

    }

    public void save(Account account) {

        try {
            //1、开启事务
            transactionManager.beginTransaction();
            //2、执行操作
            accountDao.save(account);
            //3、提交事务
            transactionManager.commitTransaction();
            //4、返回结果
            System.out.println("保存成功");

        }catch (Exception e){
            //5、回滚操作
            transactionManager.rollbackTransaction();
            e.printStackTrace();
        }finally {
            //6、释放连接
            transactionManager.release();
        }


    }

    public void update(Account account) {
        try {
            //1、开启事务
            transactionManager.beginTransaction();
            //2、执行操作
            accountDao.update(account);
            //3、提交事务
            transactionManager.commitTransaction();
            //4、返回结果
            System.out.println("更新成功。。。");

        }catch (Exception e){
            //5、回滚操作
            transactionManager.rollbackTransaction();
            e.printStackTrace();
        }finally {
            //6、释放连接
            transactionManager.release();
        }
    }

    public void delete(Integer accountId) {
        try {
            //1、开启事务
            transactionManager.beginTransaction();
            //2、执行操作
            accountDao.delete(accountId);
            //3、提交事务
            transactionManager.commitTransaction();
            //4、返回结果
            System.out.println("删除成功。。。");
        }catch (Exception e){
            //5、回滚操作
            transactionManager.rollbackTransaction();
            e.printStackTrace();
        }finally {
            //6、释放连接
            transactionManager.release();
        }
    }

    /**
     * 转账业务类
     * @param sourceName
     * @param targetName
     * @param money
     */
    public void transfer(String sourceName, String targetName, Float money) {

        try {
            //1、开始事务
            transactionManager.beginTransaction();
            //2、执行操作

            //2.1、获得用户对象
            Account sourceAccount = accountDao.findAccountByName(sourceName);
            Account targetAccount = accountDao.findAccountByName(targetName);

            //2.2、执行转账操作
            Float sourceAfterMoney = sourceAccount.getMoney() - money;
            Float targetAfterMoney = targetAccount.getMoney() + money;

            //2.3、修改对象数据
            sourceAccount.setMoney(sourceAfterMoney);
            targetAccount.setMoney(targetAfterMoney);

            //2.4、更新数据库数据
            accountDao.update(sourceAccount);
            //int a = 1/0;
            accountDao.update(targetAccount);

            //3、提交事务
            transactionManager.commitTransaction();
            //4、返回结果
            System.out.println(sourceName + "向" + targetName +"转账" + money + "元成功");

        }catch (Exception e){
            //5、回滚操作
            transactionManager.rollbackTransaction();
            e.printStackTrace();
        }finally {
            //6、断开连接
            transactionManager.release();
        }
    }
}

手动管理事务,QueryRunner要修改为使用无参的构造方法初始化,这时候需要在增删改操作方法里提供,Connection对象

package com.tianqicode.dao.Impl;

import com.tianqicode.dao.AccountDao;
import com.tianqicode.domain.Account;
import com.tianqicode.utils.ConnectionUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

//@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao {

    //调用DBUtils核心类对象
    //@Autowired
    private QueryRunner runner;

    //调用connectionUtil对象,获取链接
    private ConnectionUtil connectionUtil;

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }

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

    public List<Account> findAllAccount() {

        try {
            return runner.query(connectionUtil.getThreadLoacal(), "select * from account", new BeanListHandler<Account>(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer accountId) {
        try {
            return runner.query(connectionUtil.getThreadLoacal(), "select * from account where id = ?", new BeanHandler<Account>(Account.class),accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void save(Account account) {
        try {
            runner.update(connectionUtil.getThreadLoacal(), "insert into account(name,money)values(?,?)", account.getName(),account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

    public void delete(Integer accountId) {
        try {
            runner.update(connectionUtil.getThreadLoacal(), "delete from account where id = ?", accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过用户名查询用户对象
     * @param accountName
     * @return
     */
    public Account findAccountByName(String accountName) {
        try {
            return runner.query(connectionUtil.getThreadLoacal(), "select * from account where name = ?", new BeanHandler<Account>(Account.class),accountName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

这时候我们的项目就改造好了,在配置文件中准备相应的bean对象,注入依赖,修改注入

<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对象 -->
    <bean id="accountService" class="com.tianqicode.service.Impl.AccountServiceImpl">
        <!-- 在service类中注入dao依赖 -->
        <property name="accountDao" ref="accountDao"></property>
        <!-- 在service类中注入事务管理工具类依赖 -->
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

    <!-- 准备dao类bean对象 -->
    <bean id="accountDao" class="com.tianqicode.dao.Impl.AccountDaoImpl">
        <!-- 在dao类中注入QueryRunner依赖 -->
        <property name="runner" ref="runner"></property>
        <!-- 注入连接工具类依赖 -->
        <property name="connectionUtil" ref="connection"></property>

    </bean>

    <!-- 准备QueryRunner类bean对象 -->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>

    <!-- 准备数据源bean对象 -->
    <bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 在数据源中准备连接数据库的必要信息 -->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/javaStudy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="admin"></property>
    </bean>

    <!-- 准备连接工具类的bean对象 -->
    <bean id="connection" class="com.tianqicode.utils.ConnectionUtil">
        <!-- 注入数据源依赖 -->
        <property name="source" ref="ds"></property>
    </bean>

    <!-- 准备事务管理工具类bean对象 -->
    <bean id="transactionManager" class="com.tianqicode.utils.TransactionManager">
        <!-- 注入连接工具类对象 -->
        <property name="connectionUtil" ref="connection"></property>
    </bean>
</beans>

将算数异常注释放开,运行测试方法
此时报错,观察数据库中的数据,与操作前相同
再将算数异常注释掉再次运行,异常消失,数据正常变更

@Test
    public void  testTransfer() {

        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

        AccountService accountService = (AccountService) ac.getBean("accountService");

        accountService.transfer("TQ","YY",100f);

    }

}

到此为止,我们对于转账业务的添加就到此结束了。

  • 此时项目存在的不足
    1、代码臃肿
    2、配置文件臃肿,冗长
    3、业务类中存在对事务管理类方法的依赖(耦合)
    这些问题又如何解决呢?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值