spring 系列5 为什么在业务层用事务

前面的操作都是在持久层使用事务。下面演示一个例子:
假设账户“小王”和“小张”各1000元。
小王去银行给小张转账100元,结果应该是:小王的金额900元,而小张的金额是1100元。

如果我们这么实现,结果会怎么样?

实体类:

package com.mantishell.domain;

public class Account {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 +
                '}';
    }
}

持久层:

IAccountDao.java
package com.mantishell.dao;

import com.mantishell.domain.Account;
/**
 * 持久层接口
 */
public interface IAccountDao {

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据名称查询账户
     * @param accountName
     * @return 如果有唯一的一个结果就返回,如果没有结果就返回null
     *          如果结果集超过一个就抛异常
     */
    Account findAccountByName(String accountName);
}

AccountDaoImpl.java
package com.mantishell.dao.impl;

import com.mantishell.dao.IAccountDao;
import com.mantishell.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

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.java
package com.mantishell.service;

import com.mantishell.domain.Account;

/**
 * 业务层接口
 */
public interface IAccountService {
    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 转账
     * @param sourceName        转出账户名称
     * @param destName          转入账户名称
     * @param money             转账金额
     */
    void transfer(String sourceName,String destName,Float money);
}

AccountServiceImpl.java
package com.mantishell.service.impl;

import com.mantishell.dao.IAccountDao;
import com.mantishell.domain.Account;
import com.mantishell.service.IAccountService;


public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void transfer(String sourceName, String destName, Float money) {
        Account source = accountDao.findAccountByName(sourceName);
        Account dest = accountDao.findAccountByName(destName);
        source.setMoney(source.getMoney()-money);
        dest.setMoney(dest.getMoney()+money);
        accountDao.updateAccount(source);

        accountDao.updateAccount(dest);
    }
}

配置文件:

<?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.mantishell.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.mantishell.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <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"/>
    </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/db4"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

测试:

package com.mantishell.test;

import com.mantishell.service.IAccountService;
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;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountTest {
    @Autowired
    private IAccountService as;

    @Test
    public void testTransfer(){
        as.transfer("小王","小张",100f);
    }
}

pom文件:

    <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>
        <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>

运行测试发现竟然是正确的。但是这里不是很严谨,比如网络不是很好,导致小王把钱转出去了,但小张却没收到。那么他俩加起来的总额就不等于2000元了。
为了看的更清楚,这里在业务层的实现方法上人为造一个异常:

public void transfer(String sourceName, String destName, Float money) {
        Account source = accountDao.findAccountByName(sourceName);
        Account dest = accountDao.findAccountByName(destName);
        source.setMoney(source.getMoney()-money);
        dest.setMoney(dest.getMoney()+money);
        accountDao.updateAccount(source);
        int a = 10/0;
        accountDao.updateAccount(dest);
    }

再次测试发现,真的变成了小王的金额900元,小张的金额1000元。
难道是没用事务吗?不对啊,没有用事务的话,小王就不会减去100元了。为什么呢?
因为没有在业务层使用事务,把他俩转账捆在一起,一旦一方失败,那么数据回滚,不会造成数据错误。这就是为什么要在业务层使用事务了。

下面修改为业务层控制事务

1、添加工具类

连接工具类:

package com.mantishell.utils;

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

/**
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
 */
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.mantishell.utils;

/**
 * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
 */
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();
        }
    }
}

## 2、业务实现修改

public class AccountServiceImpl implements IAccountService {

private IAccountDao accountDao;

private TransactionManager txManager;

public void setTxManager(TransactionManager txManager) {
    this.txManager = txManager;
}

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

public void updateAccount(Account account) {
    accountDao.updateAccount(account);
}

public void transfer(String sourceName, String destName, Float money) {
    /*Account source = accountDao.findAccountByName(sourceName);
    Account dest = accountDao.findAccountByName(destName);
    source.setMoney(source.getMoney()-money);
    dest.setMoney(dest.getMoney()+money);
    accountDao.updateAccount(source);
    int a = 10/0;
    accountDao.updateAccount(dest);*/

    try {
        //1.开启事务
        txManager.beginTransaction();
        //2.执行操作
        //2.1根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根据名称查询转入账户
        Account dest = accountDao.findAccountByName(destName);
        //2.3转出账户减钱
        source.setMoney(source.getMoney()-money);
        //2.4转入账户加钱
        dest.setMoney(dest.getMoney()+money);
        //2.5更新转出账户
        accountDao.updateAccount(source);

        int i=1/0;

        //2.6更新转入账户
        accountDao.updateAccount(dest);
        //3.提交事务
        txManager.commit();

    }catch (Exception e){
        //4.回滚操作
        txManager.rollback();
        e.printStackTrace();
    }finally {
        //5.释放连接
        txManager.release();
    }
}

}


## 3、持久层修改

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

}

4、修改配置文件
<bean id="accountService" class="com.mantishell.service.impl.AccountServiceImpl">
    <!-- 注入dao -->
    <property name="accountDao" ref="accountDao"/>
    <property name="txManager" ref="txManager"/>
</bean>

<!--配置Dao对象-->
<bean id="accountDao" class="com.mantishell.dao.impl.AccountDaoImpl">
    <!-- 注入QueryRunner -->
    <property name="runner" ref="runner"/>
    <!-- 注入ConnectionUtils -->
    <property name="connectionUtils" ref="connectionUtils"/>
</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 name="jdbcUrl" value="jdbc:mysql://localhost:3306/db4?useUnicode=true&amp;characterEncoding=utf8"/>
    <property name="user" value="root"/>
    <property name="password" value="123456"/>
</bean>

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

<!-- 配置Connection的工具类 ConnectionUtils -->
<bean id="connectionUtils" class="com.mantishell.utils.ConnectionUtils">
    <!-- 注入数据源-->
    <property name="dataSource" ref="dataSource"/>
</bean>
即使我们人为在业务里添加一条异常的语句:`int i=1/0;`,执行后碰到异常,事务回滚,俩人仍然分别是1000元。

这里的service用到事务管理器,dao用到connectionutils,事务管理器也用到connectionutils,

猜你喜欢

转载自www.cnblogs.com/mantishell/p/12598812.html