JDBC工具类,基于C3P0的数据库连接池,提供获取连接池、获取连接对象、释放资源和封装事务操作的方法

/**
 *
 * JDBC工具类,基于C3P0数据库连接池的实现
 *
 * @author 周瑜
 * @2018年5月7日 下午2:13:20
 */
public final class JDBCUtils {
    /**
     * 使用C3P0-config中默认配置,创建数据库连接池对象
     */
    private static final DataSource dataSource = new ComboPooledDataSource();

    /**
     * 返回数据库连接池对象
     *
     * @return
     */
    public static final DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 定义一个ThreadLocal对象,用来保存当前线程的连接对象
     */
    private static final ThreadLocal<Connection> LOCAL = new ThreadLocal<>();

    /**
     * 返回数据库连接对象
     *
     * @throws SQLException
     */
    public static final Connection getConnection() throws SQLException {
        Connection conn = LOCAL.get();
        if (conn == null) {
            conn = dataSource.getConnection();
            LOCAL.set(conn);
        }
        return conn;
    }

    /**
     * 用于定义需要在事务中执行的逻辑代码
     *
     * @param <T>:事务中业务逻辑执行完毕后要返回的数据的类型
     * @author 周瑜
     */
    public static interface TransactionHandler<T> {
        public T execute();
    }

    /**
     * 处理事务操作
     * @param handler
     * @return
     */
    public static final <T> T executeTransaction(TransactionHandler<T> handler) {
        Connection conn = null;
        T t = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);// 开启事务
            // 执行需要在事务中执行的业务逻辑代码
            t = handler.execute();
            conn.commit();// 提交事务
        } catch (Exception e) {
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();// 回滚事务
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            // 将连接对象从ThreadLocal中移除
            LOCAL.remove();
        }
        return t;
    }
    /**
     * 关闭并释放JDBC中资源对象
     * @param closes
     */
    public static final void release(AutoCloseable... closes) {
        if(closes != null && closes.length > 0) {
            for (AutoCloseable autoCloseable : closes) {
                if(autoCloseable != null) {
                    try {
                        autoCloseable.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/zhou-yu/p/9293987.html