004-C3P0连接池工具类模板

package ${enclosing_package};

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class ${primary_type_name} {

    // 1 获得Connection ----- 从连接池中获取
    private static DataSource dataSource = new ComboPooledDataSource();

    // 2 创建ThreadLocal 存储的类型是Connection
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    // 3 直接可以获取一个连接池
    public static DataSource getDataSource() {
        return dataSource;
    }
    // 4 直接获取一个连接
    public static Connection getConnection() throws SQLException{
        return dataSource.getConnection();
    }

    // 5 获取绑定到ThreadLocal上的连接对象
    public static Connection getCurrentConnection() throws SQLException {
        //从ThreadLocal寻找 当前线程是否有对应Connection
        Connection con = tl.get();
        if (con == null) {
            //获得新的connection
            con = dataSource.getConnection();
            //将conn资源绑定到ThreadLocal(map)上
            tl.set(con);
        }
        return con;
    }

    // 6 开启事务
    public static void startTransaction() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.setAutoCommit(false);
        }
    }

    // 7 事务回滚
    public static void rollback() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.rollback();
        }
    }

    //  8 提交并且 关闭资源及从ThreadLocall中释放
    public static void commitAndRelease() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.commit(); // 事务提交
            con.close();// 关闭资源
            tl.remove();// 从线程绑定中移除
        }
    }

    // 9 关闭资源方法
    public static void close(ResultSet rs,Statement st,Connection con) throws SQLException {
        if (rs != null) {
            rs.close();
        }
        if (st != null) {
            st.close();
        }
        if (con != null) {
            con.close();
        }
    }
}
原文地址:https://www.cnblogs.com/jepson6669/p/8302345.html