JavaWeb基礎之JdbcUtils工具類final,javawebjdbcutils
JdbcUtils工具類3.0最終版,添加了事務相關功能和釋放連結。最終版本可以直接打成jar包,在後面的基本項目都會使用該工具類
1. JdbcUtils代碼
1 /** 2 * 最終版 3 * @author hui.zhang 4 * 5 */ 6 public class JdbcUtils { 7 // 設定檔的預設配置,必須給出c3p0-config.xml 8 private static ComboPooledDataSource dataSource = new ComboPooledDataSource(); 9 10 //事務專用連線11 private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();12 /**13 * 使用串連池返回一個連線物件14 * @return15 * @throws SQLException16 */17 public static Connection getConnection() throws SQLException {18 Connection con = tl.get();19 //當con比等於null,說明已經開啟了事務20 if(con != null) return con;21 return dataSource.getConnection();22 }23 24 /**25 * 返回串連池對象26 * @return27 */28 public static DataSource getDataSource() {29 return dataSource;30 }31 32 /**33 * 開啟事務34 * 1. 擷取一個Connection,設定它的setAutoCommit(false)35 * 2. 要保證dao中使用的串連是我們剛剛建立的36 * @throws SQLException 37 */38 public static void beginTransaction() throws SQLException{39 Connection con = tl.get();40 if(con != null) throw new SQLException("已經開啟了事務,請不要重複開啟!");41 con = getConnection();42 con.setAutoCommit(false);43 tl.set(con);44 }45 46 /**47 * 提交事務48 * 1. 擷取beginTransaction提供的Connection,然後調用commit方法49 * @throws SQLException 50 */51 public static void commitTransaction() throws SQLException{52 Connection con = tl.get();53 if(con == null) throw new SQLException("還沒有開啟事務,不能提交!");54 con.commit();55 con.close();56 tl.remove();57 }58 59 /**60 * 復原事務61 * 1. 擷取beginTransaction提供的Connection,然後調用rollback方法62 * @throws SQLException 63 */64 public static void rollbackTransaction() throws SQLException{65 Connection con = tl.get();66 if(con == null) throw new SQLException("還沒有開啟事務,不能復原!");67 con.rollback();68 con.close();69 tl.remove();70 }71 72 /**73 * 釋放串連74 * @param connection75 * @throws SQLException 76 */77 public static void releaseConnection(Connection connection) throws SQLException{78 Connection con = tl.get();79 //判斷是不是事務專用連線,如果是不用關80 if(con == null)81 connection.close();82 //如果con != null,說明有事務,需要判斷參數串連是否與con相同83 //不同 說明不是事務專用連結84 if(con != connection)85 connection.close();86 }87 }
2. 在src下給出c3p0-config.xml設定檔
<?xml version="1.0" encoding="UTF-8"?><c3p0-config> <!-- 預設配置資訊 --> <default-config> <!-- 串連四大參數 --> <property name="user">root</property> <property name="password">123</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///mydb</property> <!-- 池參數配置 --> <property name="acquireIncrement">3</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">2</property> <property name="maxPoolSize">10</property> </default-config></c3p0-config>
3. 總結
從第一個基本版本1.0到加入串連池2.0再到現在的事務,一步一個腳印。每個版本都應該留下。。。溫故而知新!!!