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

此時事務控制成功,但是我們發現當前程序非常的臃腫。

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