spring框架学习-个人案例ioc(xml),添加转账方法,并且演示事务

1.基于:https://www.cnblogs.com/ccoonngg/p/11223340.html

2.在AccountService接口中增加transfer方法

    /**
     * 转账
     * @param sourceId  转出账户
     * @param targetId  转入账户
     * @param money     转账金额
     */
    void transfer(int sourceId,int targetId,float money);

3.在AccountServiceImpl类中增加实现方法

    @Override
    public void transfer(int sourceId, int targetId, float money) {
        //1.查找转账账户
        Account sourceAccount = accountDao.findAccountById(sourceId);
        //2.查找转入账户
        Account targetAccount = accountDao.findAccountById(targetId);
        //3.转出账户减少金额
        sourceAccount.setMoney(sourceAccount.getMoney() - money);
        //4.转入账户增减金额
        targetAccount.setMoney(targetAccount.getMoney() + money);
        //5.更新转出账户
        accountDao.updateAccount(sourceAccount);
        //6.更新转入账户
        accountDao.updateAccount(targetAccount);
    }

4.在测试类中增加单元测试

    @Test
    public void transfer(){
       as.transfer(1,2,100);
    }

5.执行单元测试前后数据库内容

6.但是,如果在AccountServiceImpl中的第六步之前插入一个会出错的语句,比如

        //5.更新转出账户
        accountDao.updateAccount(sourceAccount);
        int i = 1/0;
        //6.更新转入账户
        accountDao.updateAccount(targetAccount);

7.那么再进行一次单元测试,结果如下

因为在更新转出账户之前,程序出错了,停止运行了,但是之前的都已经执行了

也就是没有事务的支持

原因

根据目前的配置方式,Dbutils的配置对象QueryRunner每次都会创建一个新的QueryRunner

并且在执行操作的时候每次都从数据源中拿出一个连接对象

<!--配置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/cong"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>

通过下图可以看出它与数据库交互了几次

每个连接都有自己的独立事务

比如转出账户减少金额成功了,然后提交

比如转入账户增加金额因为int i = 1/0,失败了,然后提交

结果,两个操作独立提交,在数据库的实际操作中就会出现减少的减少了,增加的没有增加

解决的思路就是这些操作全部由同一个connection控制

也就是使用ThreadLocal对象绑定线程

 

8.改进,改进的代码变得面目全非

所以干脆当作一个新的项目来讲

1.创建maven项目,导入相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cong</groupId>
    <artifactId>spring_accountTransfer_transaction</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- dbutils的依赖 -->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- 连接池的依赖 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>

2.在java目录下创建com.cong.utils.ConnectionUtils类

整个ConnectionUtils的作用就是保证当前线程(比如转账操作就可以看作是一个线程)使用的是同一个连接

然后提供一个解除当前线程上的连接的方法

package com.cong.utils;

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

/**
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
 * 事务的控制由connection决定,事务的控制另外写一个TransactionManager类
 * DbUtils中使用ThreadLocal对象把connection和当前线程绑定,从而使一个线程中只有一个能控制事务的对象
 */
public class ConnectionUtils {
    //需要一个Connection类型的ThreadLocal,直接实例化出来
    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    //这个DataSource不能new,只能等着spring为我们注入,所以需要seter方法
    private DataSource dataSource;
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    //获取当前线程的连接
    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);
        }
    }

    /**
     * 把连接和线程解绑
     * 细节:
     * 连接使用了连接池,连接池的好处是把消耗时间获取连接的这一部分
     * 放到应用加载一开始,在web工程中,当我们启动tomcat服务器的时候,加载应用时,会创建一些连接
     * 从而在后续需要连接的时候,不再从数据库获取连接,而是直接从线程池中拿,保证效率
     * 同理
     * 我们使用服务器,也有一个类似的技术,叫做线程池
     * 特点是当tomcat一启动时,会初始化一些线程,放到一个容器中
     * 然后每次访问,都是从线程池中拿出一个线程,给我们使用
     * 连接用完了,还回到连接池中,线程一样,也会还回到线程池里面
     * 但是线程是绑定一个连接的
     * 当我们把连接关闭,线程还回到线程池中时,线程是有连接的,
     * 但我们下次获取一个线程,判断上面有没有连接时,得到的结果一定是有
     * 只不过这个连接已经被close过了,不能再用了
     * 所以在整个线程用完之后,需要对这个连接做一个解绑操作
     * 虽然这是一个java工程,是不涉及这个问题的,但是要养成习惯
     * 当改成web工程的时候,会涉及到这个问题
     */
    public void removeConnection() {
        tl.remove();//把连接和线程解绑
    }
}

3.在utils包下创建TransactionManager类

这个类的作用就是事务控制,包括开启事务,提交事务,回滚事务,以及释放连接和解除连接与当前线程的绑定

package com.cong.utils;

/**
 * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
 * 这个类如何执行呢?与事务相关,首先要有connection,并且是当前线程的connection
 * 所以需要用到ConnectionUtils类
 * 并且提供一个setter方法,等着spring注入
 */
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();
        }
    }
}

4.在java目录下创建com.cong.pojo.Account类

package com.cong.pojo;

public class Account {
    private int id;
    private String name;
    private float money;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

5.在java目录下创建com.cong.dao包,并且创建Account持久层相关的接口和类

在前面的项目中,我们没有添加事务控制,QurryRunner由spring注入,会自动从连接池中获取连接

比如在转账过程中,有6个操作,这几个操作都自动从连接池中获取,也就是会有独立的连接

如果添加了事务控制,这明显与事务的原子性不符合

因此在AccountDaoImpl中添加一个ConnectionUtils对象,用来获取当前线程上的连接,保证整个操作用到的是同一个连接

并且在bean.xml中取消QurryRunner的自动注入

连接1.查询转出账户

连接2.查询转入账户

连接3.转出账户更新

连接4.转入账户更新

AccountDao接口

package com.cong.dao;

import com.cong.pojo.Account;

import java.util.List;

public interface AccountDao {
    List<Account> findAllAccount();//find all
    Account findAccountById(int id);//find one
    void saveAccount(Account account);//save
    void updateAccount(Account account);//update
    void deleteAccount(int id);//delete
}

AccountDaoImpl类

package com.cong.dao;

import com.cong.pojo.Account;
import com.cong.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;
/**
 * 从bean.xml中可以发现
 * <bean id="accountDao" class="com.cong.dao.AccountDaoImpl">
 <property name="runner" ref="runner"></property>
 * </bean>
 * <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
 *      <constructor-arg name="ds" ref="dataSource"></constructor-arg>
 * </bean>
 * accountDao注入了一个QueryRunner对象,QueryRunner就会从连接池里面自动获取一个连接
 * 但是我们现在需要用到事务,事务管理就必须保证整个操作用到的是同一个connection
 * (转账操作中有好几个步骤需要用到connection)
 * 于是不希望它从连接池里面自动获取,所以需要在AccountDaoImpl里面有一个ConnectionUtils对象,
 * 用来获取  当前线程上面的   连接
 * 然后需要对runner的query方法添加一个连接的参数
 */
public class AccountDaoImpl implements AccountDao {
    private QueryRunner runner;
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }
    private ConnectionUtils connectionUtils;
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

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

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

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

    @Override
    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);
        }
    }

    @Override
    public void deleteAccount(int id) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"delete from account where id = ?",id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

6.在java目录下创建com.cong.service,并且创建服务层相关的接口和类

package com.cong.service;

import com.cong.pojo.Account;

import java.util.List;

public interface AccountService {
    List<Account> findAllAccount();//find all
    Account findAccountById(int id);//find one
    void saveAccount(Account account);//save
    void updateAccount(Account account);//update
    void deleteAccount(int id);//delete
    /**
     * 转账
     * @param sourceId  转出账户
     * @param targetId  转入账户
     * @param money     转账金额
     */
    void transfer(int sourceId, int targetId, float money);
}



package com.cong.service;

import com.cong.dao.AccountDao;
import com.cong.pojo.Account;
import com.cong.utils.TransactionManager;

import java.util.List;

/**
 * 账户的业务层实现类
 * 事务控制应该都在业务层的
 */
public class AccountServiceImpl implements AccountService {
    //业务层都是调用持久层的,所以需要有一个持久层的对象
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    //添加事务支持需要用到TransactionManager的对象,这个对象不能自己创建,只能有spring注入,所以有setter方法
    private TransactionManager tm;
    public void setTm(TransactionManager tm) {
        this.tm = tm;
    }

    /**
     * 以下所有操作都可以加上事务控制
     * 开启事务,执行操作,提交事务(返回结果),回滚操作,关闭事务
     */
    @Override
    public List<Account> findAllAccount() {
        try {
            //1.开启事务
            tm.beginTransaction();
            //2.执行操作
            List<Account> accounts = accountDao.findAllAccount();
            //3.提交事务
            tm.commit();
            //4.返回结果
            return accounts;
        }catch (Exception e){
            //5.回滚操作
            tm.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.关闭事务
            tm.release();
        }
    }

    @Override
    public Account findAccountById(int id) {
        try {
            //1.开启事务
            tm.beginTransaction();
            //2.执行操作
            Account account = accountDao.findAccountById(id);
            //3.提交事务
            tm.commit();
            //4.返回结果
            return account;
        }catch (Exception e){
            //5.回滚操作
            tm.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.关闭事务
            tm.release();
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            //1.开启事务
            tm.beginTransaction();
            //2.执行操作
            accountDao.saveAccount(account);
            //3.提交事务
            tm.commit();
        }catch (Exception e){
            //5.回滚操作
            tm.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.关闭事务
            tm.release();
        }

    }

    @Override
    public void updateAccount(Account account) {
        try {
            //1.开启事务
            tm.beginTransaction();
            //2.执行操作
            accountDao.updateAccount(account);
            //3.提交事务
            tm.commit();
        }catch (Exception e){
            //5.回滚操作
            tm.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.关闭事务
            tm.release();
        }

    }

    @Override
    public void deleteAccount(int id) {
        try {
            //1.开启事务
            tm.beginTransaction();
            //2.执行操作
            accountDao.deleteAccount(id);
            //3.提交事务
            tm.commit();
        }catch (Exception e){
            //5.回滚操作
            tm.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.关闭事务
            tm.release();
        }
    }

    @Override
    public void transfer(int sourceId, int targetId, float money) {
        try {
            //1.开启事务
            tm.beginTransaction();
            //2.执行操作
            //2.1.查找转账账户
            Account sourceAccount = accountDao.findAccountById(sourceId);
            //2.2.查找转入账户
            Account targetAccount = accountDao.findAccountById(targetId);
            //2.3.转出账户减少金额
            sourceAccount.setMoney(sourceAccount.getMoney() - money);
            //2.4.转入账户增减金额
            targetAccount.setMoney(targetAccount.getMoney() + money);
            //2.5.更新转出账户
            accountDao.updateAccount(sourceAccount);
            //2.6.更新转入账户
            accountDao.updateAccount(targetAccount);
            //3.提交事务
            tm.commit();
        }catch (Exception e){
            //5.回滚操作
            tm.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.关闭事务
            tm.release();
        }
    }
}

7.在resources下创建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.cong.service.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
        <property name="tm" ref="tm"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.cong.dao.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
        <property name="connectionUtils" ref="connectionUtils"></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/cong"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
    <bean id="connectionUtils" class="com.cong.utils.ConnectionUtils">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="tm" class="com.cong.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
</beans>

8.在test,java下创建测试类

import com.cong.pojo.Account;
import com.cong.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    AccountService as;
    @Test
    public void transfer(){
        as.transfer(1,2,100);
    }
   @Test
    public void testFindAll(){
       List<Account> list = as.findAllAccount();
       for (Account account : list) {
           System.out.println(account.toString());
       }
   }
    @Test
    public void testFindOne(){
        Account account = as.findAccountById(1);
        System.out.println(account.toString());
    }
    @Test
    public void testSave(){
       Account account = new Account();
       account.setName("cong");
       account.setMoney(5);
       as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        Account account = new Account();
        account.setName("rainbow");
        account.setMoney(50000);
        account.setId(3);
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        as.deleteAccount(4);
    }
}

9.单元测试transfer,前后结果

10.一样,在转账的过程中添加一个会出错的语句

            //2.5.更新转出账户
            int i = 1/0;
            accountDao.updateAccount(sourceAccount);
            //2.6.更新转入账户
            accountDao.updateAccount(targetAccount);

11.运行结果,程序报错,数据库中的内容没有改变

 

 11.以上案例虽然添加了事务管理,但是有一些弊端‘

  *配置文件非常麻烦,很多依赖注入乱七八糟

  *service用到事务管理器TransactionManager,dao用到connectionUtils

  * 事务管理器也用到connectionUtils,它们之间都有一些互相依赖

  *更重要的是AccountServiceImpl中代码有很多的重复

所以就需要用到aop,还有spring的事务管理

移步:https://www.cnblogs.com/ccoonngg/p/11244441.html

转载于:https://www.cnblogs.com/ccoonngg/p/11229393.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值