1. 程式人生 > >Java練習筆記 -ThreadLocal的一種應用場景

Java練習筆記 -ThreadLocal的一種應用場景

用ThreadLocal來儲存資料庫連線

程式碼如下

public class DataSourceUtils {


private static DataSource dataSource = new ComboPooledDataSource();


private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();


public static DataSource getDataSource() {
return dataSource;
}


/**
* 當DBUtils需要手動控制事務時,呼叫該方法獲得一個連線

* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {


Connection con = tl.get();


if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}


return con;
}


// 開啟事務
public static void startTransaction() throws SQLException {


getConnection().setAutoCommit(false); //設定事務為手動事務,相當於開啟事務


}


// 事務回滾
public static void rollback() throws SQLException {
getConnection().rollback();
}


// 事務提交
public static void commitAndReleased() throws SQLException {


getConnection().commit(); // 事務提交
getConnection().close();// 釋放connection,是將其放回到連線池.
tl.remove();
}


}