/**
* 工具类 提供数据库连接池 和数据库连接
*/
public class JDBCUtils {
private static DataSource dataSource = new ComboPooledDataSource();
public static DataSource getDataSource() {
return dataSource;
}
/**
* 当DBUtils需要手动控制事务时,调用该方法获得一个连接
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
public class TransactionUtils {
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
public synchronized static Connection getConnection() throws SQLException{
if(threadLocal.get() == null){
threadLocal.set(JDBCUtils.getConnection());
}
return threadLocal.get();
}
public static synchronized void commitAndClose(){
Connection conn = threadLocal.get();
try {
conn.commit();
conn.close();
threadLocal.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static synchronized void roolbackAndClose(){
Connection conn = threadLocal.get();
try {
conn.rollback();
conn.setAutoCommit(true);
conn.close();
threadLocal.remove();
} catch(SQLException e){
e.printStackTrace();
}
}
}