package com.itheima.util; import java.sql.Connection; import java.sql.SQLException; //封裝了全部與事務有關的方法 public class TransactionManager { private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); public static Connection getConnection(){ Connection conn = tl.get(); if(conn==null){//從當前線程中獲取連接 conn = DBCPUtil.getConnection(); tl.set(conn); } return conn; } public static void startTransaction(){ try { Connection conn = getConnection(); conn.setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } public static void rollback(){ try { Connection conn = getConnection(); conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } } public static void commit(){ try { Connection conn = getConnection(); conn.commit(); } catch (SQLException e) { e.printStackTrace(); } } public static void release(){ try { Connection conn = getConnection(); conn.close(); tl.remove();//從當前線程中解綁。 與服務器實現有關:服務器採用線程池。 } catch (SQLException e) { e.printStackTrace(); } } }