jdbc事务封装之DBCPUtil和ThreadLocal

1.封装DBCPUtil工具类

package com.itheima.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtil {
    private static DataSource dataSource;
    static{
        try {
            //读取配置文件,初始化数据源
            InputStream in = DBCPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties props = new Properties();
            props.load(in);
            dataSource = BasicDataSourceFactory.createDataSource(props);
        }  catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }

    }

    public static DataSource getDataSource(){
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败");
        }
    }

}

2.封装ThreadLocal事务管理器

package com.itheima.util;

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

//事务管理器
public class TransationManager {

    private static ThreadLocal tl = new ThreadLocal();

    public static Connection getConnection() {
        Connection conn = tl.get();// 从当前线程上获得链接
        if (conn == null) {
            conn = DBCPUtil.getConnection();
            tl.set(conn);// 把链接绑定到当前线程上
        }
        return conn;
    }

    public static void startTransaction() {
        Connection conn = getConnection();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit() {
        Connection conn = getConnection();
        try {
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback() {
        Connection conn = getConnection();
        try {
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void release() {
        Connection conn = getConnection();
        try {
            conn.close();
            tl.remove();// 与线程池有关,解除关系
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3.使用ThreadLocal后在开发中service层中的应用
jdbc事务封装之DBCPUtil和ThreadLocal_第1张图片
jdbc事务封装之DBCPUtil和ThreadLocal_第2张图片

4.为了对比来一个没有使用ThreadLocal的传统事务控制
jdbc事务封装之DBCPUtil和ThreadLocal_第3张图片
jdbc事务封装之DBCPUtil和ThreadLocal_第4张图片

你可能感兴趣的:(Java)