事务操作案例

这篇博客介绍了在Java中进行事务操作的案例,重点讨论了如何利用ThreadLocal存储和管理数据库连接,以避免在服务层和DAO层之间传递Connection对象。文章详细展示了AccountDao、AccountService和AccountTest的实现过程,并解释了改写C3P0Utils工具类来支持ThreadLocal的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

事务案例

1.AccountDao
2.AccountService
3.AccountTest

Account

package bull07.dao;

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

import org.apache.commons.dbutils.QueryRunner;

public class AccountDao {
    public void out(Connection conn ,String outUser, Double money) throws SQLException {
        //获得连接
        //传进了conn,所以不用提供数据源。
        QueryRunner queryRunner = new QueryRunner();
        //SQL语句
        String sql = "update account set money = money + ? where name = ?;";
        //实际参数
        Object[] param = {money,outUser};
        //执行
        queryRunner.update(conn,sql, param);
    }

    public void in(Connection conn ,String inUser, Double money) throws SQLException {
        QueryRunner queryRunner = new QueryRunner();
        String sql = "update account set money = money - ? where name = ?;";
        Object[] param = {money,inUser};
        queryRunner.update(conn,sql, param);
    }
}

AccountService

package bull07.service;

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

import org.apache.commons.dbutils.DbUtils;

import bull03.C3P0.C3P0Utils;
import bull07.dao.AccountDao;

public class AccountService {
    public void transfer(String outUser,String inUser,Double money) {   
        Connection conn = null;
        try {
            //获得连接
            conn = C3P0Utils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //业务操作
            AccountDao accountDao = new AccountDao();
            accountDao.out(conn,outUser,money);
            //模拟异常
            //int i = 1/0;
            accountDao.in(conn,inUser, money);

            //提交事务并释放资源
            DbUtils.commitAndCloseQuietly(conn);
        } catch (Exception e) {
            // 事务回滚
            DbUtils.rollbackAndCloseQuietly(conn);
            throw new RuntimeException(e);
        }
    }
}

AccountTest

package bull07.test;

import java.sql.SQLException;

import bull07.service.AccountService;

public class AccountTest {
    public static void main(String[] args) {
        String outUser = "rose";
        String inUser = "jack";
        Double money = 200.0;
        try {
            AccountService accountService = new AccountService();
            accountService.transfer(outUser, inUser, money);
            System.out.println("转账成功!");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("转账失败!");
        }
    }
}

采用ThreadLocal实现

  • 改写C3P0Utils工具类,将连接存到ThreadLocal中,同个线程通过工具类中获取相同连接,与此前相比不用传递Connection对象。
    这里写图片描述
    这里写图片描述

改写C3P0Utils

package bull08.ThreadLocal;
/*
 * C3P0工具类
 */
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {
    //连接池
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource("bull");
    //给当前线程绑定连接
    private static ThreadLocal<Connection> local = new ThreadLocal<Connection>();

    public static Connection getConnection() {
        //从当前的线程中获得已经绑定的连接
        Connection conn = local.get();
        try {
            if(conn == null) {
                //第一次从连接池中获得
                conn =  dataSource.getConnection();
                //将连接存ThreadLocal中                                                   
                local.set(conn);
            }
            return conn;//获得连接
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

AccountDao

package bull08.ThreadLocal;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;

/*
 * 不用传递conn连接,连接保存到ThreadLocal,从工具类中获取连接:C3P0Utils.getConnection()。
 */
public class AccountDao {
    public void out(String outUser ,Double money) throws SQLException {
        QueryRunner queryRunner = new QueryRunner();
        //sql
        String sql = "update account set money = money + ? where name = ?;";
        //实际参数
        Object[] params = {money,outUser};
        //执行
        queryRunner.update(C3P0Utils.getConnection(), sql, params);
    }

    public void in(String inUser ,Double money) throws SQLException {
        QueryRunner queryRunner = new QueryRunner();
        String sql = "update account set money = money - ? where name = ?;";
        Object[] params = {money,inUser};
        queryRunner.update(C3P0Utils.getConnection(), sql, params);
    }
}

AccountService

package bull08.ThreadLocal;

import java.sql.Connection;

import org.apache.commons.dbutils.DbUtils;

public class AccountService {
    public void transfer(String outUser ,String inUser ,Double money) {
        Connection conn = null;
        try {
            //获得连接
            conn = C3P0Utils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //业务操作
            AccountDao accountDao = new AccountDao();
            accountDao.out(outUser, money);
            accountDao.in(inUser, money);
            //提交事务
            DbUtils.commitAndCloseQuietly(conn);
        } catch (Exception e) {
            // 事务回滚
            DbUtils.rollbackAndCloseQuietly(conn);
            throw new RuntimeException(e);
        }
    }
}

AccountTest

package bull08.ThreadLocal;

public class AccountTest {
    public static void main(String[] args) {
        String outUser = "jack";
        String inUser = "rose";
        Double money = 100.0;
        try {
            AccountService accountService = new AccountService();
            accountService.transfer(outUser, inUser, money);
            //成功的话输出转账成功。
            System.out.println("转账成功!");
        } catch (Exception e) {
            // 出现异常的话则输出转账失败。
            System.out.println("转账失败!");
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值