1. 程式人生 > >使用ThreadLocal實現對JDBC的事務處理

使用ThreadLocal實現對JDBC的事務處理

一、準備工作
在應用ThreadLocal對JDBC的事務處理前,可以先在專案中匯入資料庫連線池的jar包,然後建立c3p0-config.xml並配置。

二、建立使用ThreadLocal的事務處理工具類

public class JDBCUtils3 {

    private static DataSource dataSource=null;
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();//使用ThreadLocal儲存當前執行緒中的Connection物件
static{ dataSource=new ComboPooledDataSource();//建立C3P0資料庫連線池 } public static Connection getConnection() throws Exception{ //從當前執行緒中獲取Connection Connection conn = threadLocal.get(); if(conn==null){ //從資料來源中獲取資料庫連線 conn = getDataSource().getConnection(); //將conn繫結到當前執行緒
threadLocal.set(conn); } return conn; } //開啟事務的操作 public static void startTransaction(){ Connection connection=threadLocal.get(); if(null == connection){ try { connection=getDataSource().getConnection(); } catch
(SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } threadLocal.set(connection); //把資料庫連線繫結到當前執行緒上 } try { connection.setAutoCommit(false); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //事務提交 public static void commit(){ Connection connection = threadLocal.get(); if(null != connection){ try { connection.commit(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //事務回滾 public static void rollback(){ Connection connection = threadLocal.get(); if(null != connection){ try { connection.rollback(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //關閉的方法 public static void close(){ try{ //從當前執行緒中獲取Connection Connection conn = threadLocal.get(); if(conn!=null){ threadLocal.remove(); //解除當前執行緒上繫結的連線 conn.close(); } }catch (Exception e) { throw new RuntimeException(e); } } //從資料來源中獲取資料庫連線 public static DataSource getDataSource(){ return dataSource; } }

三、業務層使用工具類實現事務處理

public void buyFund(String uname, Integer mid, Integer buynum) {
        User user = fundDaoImpl.getUserByName(uname);
        Integer uid = user.getUid();        
        try {
            JDBCUtils3.startTransaction();
            fundDaoImpl.buyFundOnUser(uid,mid,buynum);

            fundDaoImpl.buyFundOnMoney(mid,buynum);
            JDBCUtils3.commit();            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            JDBCUtils3.rollback();

        }finally {
            JDBCUtils3.close();
        }

    }