09.dbutils-转账案例-有事务方式

 

 

 

demo1.java

复制代码
package com.exp.demo1;

import org.junit.Test;

import com.exp.service.IAccountService;
import com.exp.service.impl.AccountServiceImpl;

public class demo1 {
    @Test
    public void test1(){
        IAccountService accountService = new AccountServiceImpl();
        accountService.transfer("aaa", "bbb", 100);
    }
    @Test
    public void test2(){
        IAccountService accountService = new AccountServiceImpl();
        accountService.transfer1("aaa", "bbb", 100);
    }
}
复制代码

 

 

IAccountService.java

复制代码
package com.exp.service;

public interface IAccountService {
    /*
     * 转账操作
     * @param from
     * @param to
     * @param account
     */
    public void transfer(String from,String to,double amount);
    public void transfer1(String from,String to,double amount);
}
复制代码

 

 

AccountServiceImpl.java

复制代码
package com.exp.service.impl;

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

import com.exp.dao.IAccountDao;
import com.exp.dao.impl.AccountDaoImpl;
import com.exp.model.Account;
import com.exp.service.IAccountService;
import com.exp.utils.ManagerThreadLocal;

public class AccountServiceImpl implements IAccountService{
    
    @Override
    public void transfer(String from, String to, double amount){
        try {
            IAccountDao accountDao = new AccountDaoImpl();
            accountDao.updateAccount(from, to, amount);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void transfer1(String from, String to, double amount) {
        Connection conn = null;
        try {
            //本地线程获取连接
            ManagerThreadLocal.getConnection();
            IAccountDao accountDao = new AccountDaoImpl();
            
            //开启事务
            ManagerThreadLocal.beginTransaction();
            
            
            //1、获取from的账号信息
            Account fromAccount = accountDao.findAccount(from);
            
            //2、获取to的账号信息
            Account toAccount = accountDao.findAccount(to);
            
            System.out.println("转账前....");
            System.out.println("from:" + fromAccount);
            System.out.println("to:" + toAccount);
            
            //3.修改Model的money金额
            System.out.println("转账后....");
            fromAccount.setMoney(fromAccount.getMoney()-amount);
            toAccount.setMoney(toAccount.getMoney()+amount);
            System.out.println("from:" + fromAccount);
            System.out.println("to:" + toAccount);
            
            //4.操作数据库【把数据保存到数据库】
            accountDao.updateAccount(fromAccount);
            //int i = 10/0;
            accountDao.updateAccount(toAccount);
            
            //提交事务
            ManagerThreadLocal.commitTransaction();
            
        } catch (Exception e) {
                //回滚事务
            ManagerThreadLocal.rollbackTransaction();
            e.printStackTrace();
        }finally{
                //关闭资源
                ManagerThreadLocal.close();

        }
        
    }

}
复制代码

 

 

IAccountDao.java

复制代码
package com.exp.dao;

import java.sql.SQLException;

import com.exp.model.Account;

public interface IAccountDao {
    /**
     * 更新账户信息
     * @param from 输出的帐号
     * @param to 输入的帐号
     * @param amount 转账的金额
     */
    public void updateAccount(String from,String to,double amount)throws SQLException;

    
    /**
     * 根据名字查找账号信息
     * @param name
     * @return
     */
    public Account findAccount(String name)throws SQLException;
    
    public void updateAccount(Account account)throws SQLException;
}
复制代码

 

 

AccountDaoImpl.java

复制代码
package com.exp.dao.impl;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.exp.dao.IAccountDao;
import com.exp.model.Account;
import com.exp.utils.C3P0Utils;
import com.exp.utils.ManagerThreadLocal;

public class AccountDaoImpl implements IAccountDao{

    @Override
    public void updateAccount(String from, String to, double amount) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        //执行2条sql语句
        qr.update("update account set money=money-? where name =?",amount,from);
        int i = 10/0;
        qr.update("update account set money=money+? where name =?",amount,to);
        
    }

    //=========================使用数据源执行方式
    @Override
    public Account findAccount(String name) throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "select * from account where name=?";
        Account account = qr.query(ManagerThreadLocal.getConnection(),sql, new BeanHandler<Account>(Account.class),name);
        return account;
    }

    @Override
    public void updateAccount(Account account) throws SQLException {
        QueryRunner qr = new QueryRunner();
        qr.update(ManagerThreadLocal.getConnection(),"update account set money = ? where id = ?",account.getMoney(),account.getId());
    }
}
复制代码

 

 

 

ManagerThreadLocal.java   //本地线程管理

复制代码
package com.exp.utils;

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

public class ManagerThreadLocal {

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    
    public static Connection getConnection(){
        try {
            Connection conn = tl.get();
            
            //第一次是空
            if(conn == null){
                //从数据源取
                conn = C3P0Utils.getConnection();
                tl.set(conn);
                System.out.println("第一次从数据源获取connection对象:" + conn);
            }else{
                //System.out.println("第n次从ThreadLocal获取connection对象");
            }
            
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    /**
     * 开启事务
     */
    public static void beginTransaction(){
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * 回滚事务
     */
    public static void rollbackTransaction(){
        try {
            getConnection().rollback();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    /**
     * 提交事务
     */
    public static void commitTransaction(){
        try {
            getConnection().commit();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * 关闭连接
     */
    public static void close(){
        try {
            getConnection().close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
复制代码

 

posted @   expworld  阅读(130)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示