ThreadLocal 实例通常是类中的私有静态字段,一般用于存储与线程关联的局部变量。
这是个DB工具类,看明白你就知道了。
public class DB {
private static DataSource ds;
private static ThreadLocal
static {
ds = new ComboPooledDataSource();
}
//防止实例
private DB(){
}
public static DataSource getDataSource() {
return ds;
}
/***
* 从连接池获取conn连接
* @return
*/
public static Connection getConnection() {
try {
// 得到当前线程上绑定的连接
Connection conn = threadLocal.get();
if (conn == null) { // 代表线程上没有绑定连接
conn = ds.getConnection();
threadLocal.set(conn);
}
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/***
* 开启事务
*/
public static void beginTransaction() {
try {
// 得到当前线程上绑定连接开启事务
Connection conn = getConnection();
if(!conn.getAutoCommit()){
logger.warn(" connection got the last autoCommit value ! ");
}
conn.setAutoCommit(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 提交事务
*/
public static void commitTransaction() {
try {
Connection conn = threadLocal.get();
if (conn != null) {
conn.commit();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/***
* 关闭连接
*/
public static void closeConnection() {
try {
Connection conn = threadLocal.get();
if (conn != null) {
conn.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
threadLocal.remove();
}
}
/***
* 关闭连接
*/
public static void rollback() {
try {
Connection conn = threadLocal.get();
if (conn != null) {
conn.rollback();;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}