Spring5(8)- 轉賬案例演示事務問題

1 沒有事務的轉賬案例

1.1 DAO 實現類

 @Override
    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;
            } else if (accounts.size() > 1) {
                throw new RuntimeException("返回結果大於一個");
            }
            return accounts.get(0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

1.2 Service 實現類

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        // 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 = 100 / 0;

        // 6.更新轉入賬戶
        accountDao.updateAccount(target);

    }

1.3 單元測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

   @Autowired
    private IAccountService as;

   public void testTransfer(){
       as.transfer("Mike","Jenny",100f);
   }

}

在這裏插入圖片描述


在這裏插入圖片描述
在這裏插入圖片描述

2 分析事物問題

在這裏插入圖片描述

2.1 ConnectionUtils

package com.tzb.utils;

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

/**
 * 連接的工具類
 */
public class ConnectionUtils {
    private ThreadLocal<Connection> tl = new ThreadLocal<>();

    private DataSource dataSource;

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

    /**
     * 獲取當前線程的連接
     *
     * @return
     */
    public Connection getThreadConnection() {
        Connection conn = tl.get();

        try {
            if (null == conn) {
                // 從數據源獲取一個連接,並存入ThreadLocal
                conn = dataSource.getConnection();
                tl.set(conn);
            }
            return conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
/**
     * 把連接和線程解綁
     */
    public void removeConnection(){
        tl.remove();
    }
}

2.2 事務管理類

package com.tzb.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.3 在業務層和持久層添加事務控制

2.3.1 DAO

package com.tzb.dao.impl;

import com.tzb.dao.IAccountDao;
import com.tzb.domain.Account;
import com.tzb.utils.ConnectionUtils;
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;

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

    @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(Integer accountId) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?", accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

    @Override
    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;
            } else if (accounts.size() > 1) {
                throw new RuntimeException("返回結果大於一個");
            }
            return accounts.get(0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

2.3.2 Service

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

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

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

    @Override
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }

    @Override
    public Account findAccountById(Integer accountId) {
       return accountDao.findAccountById(accountId);
    }

    @Override
    public List<Account> findAllAccount() {

        try{
            //1.開啓事務
            txManager.beginTransaction();

            //2.執行操作
           List<Account> accounts = accountDao.findAllAccount();

            //3.提交事務
            txManager.commit();

            //4.返回結果
            return accounts;
        }catch (Exception e){
            // 5.回滾操作
            txManager.rollback();
            throw new RuntimeException(e);
        }finally {
            // 6.釋放連接
            txManager.release();
        }

    }

    @Override
    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 = 100 / 0;

            // 2-6.更新轉入賬戶
            accountDao.updateAccount(target);

            //3.提交事務
            txManager.commit();

        }catch (Exception e){
            // 5.回滾操作
            txManager.rollback();
            e.printStackTrace();
        }finally {
            // 6.釋放連接
            txManager.release();
        }

    }
}

2.3.3 bean.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--導入 spring 約束-->
<!--基於註解的IOC配置需要導入 context 名稱空間-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="accountService" class="com.tzb.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
        <property name="txManager" ref="transactionManager"></property>
    </bean>
    
    <bean id="accountDao" class="com.tzb.dao.impl.AccountDaoImpl">
        <property name="runner" ref="runner"></property>
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>

    <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/spring5?userSSL=false"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="connectionUtils" class="com.tzb.utils.ConnectionUtils" >
        <!--注入數據源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

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

2.3.4 單元測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

   @Autowired
    private IAccountService as;

   @Test
   public void testTransfer(){
       as.transfer("Mike","Jenny",100f);
   }

}

在這裏插入圖片描述

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