我們來寫一個Jdbc工具類——JdbcUtils
這個工具類可以用來獲取Connection對象,以及開啟和關閉事物,所以這個工具類用到連接mysql的驅動jar包,涉及c3p0連接池,所以還需要導入c3p0的jar包,以及c3p0-config.xml配置文件,獲取連接時用到了ThreadLocal。
涉及jar包:
c3p0-0.9.2-pre1.jar
mchange-commons-0.2.jar
mysql-connector-java-5.1.13-bin.jar
JdbcUtils中的方法
- Connection getConnection()
此方法從c3p0連接池獲取Connection對象,所以需要提供c3
p0-config.xml配置文件 - beginTransaction()
為當前線程開啟事務 - commitTransaction()
提交當前線程的事物 - rollbackTransaction()
回滾當前線程的事物 - releaseConnection(Connection)
如果參數連接對象不是當前事務的連接對象,那么關閉,否則什么都不做
下面是c3p0-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcUtils</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</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>
代碼
package com.java.jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtils {
// 餓漢式
private static DataSource ds = new ComboPooledDataSource();
/**
* 它為null表示沒有事務
* 它不為null表示有事務
* 當開啟事務時,需要給它賦值
* 當結束事務時,需要給它賦值為null
* 并且在開啟事務時,讓dao的多個方法共享這個Connection
*/
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
public static DataSource getDataSource() {
return ds;
}
/**
* dao使用本方法來獲取連接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
/*
* 如果有事務,返回當前事務的con
* 如果沒有事務,通過連接池返回新的con
*/
Connection con = tl.get();//獲取當前線程的事務連接
if(con != null) return con;
return ds.getConnection();
}
/**
* 開啟事務
* @throws SQLException
*/
public static void beginTransaction() throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(con != null) throw new SQLException("已經開啟了事務,不能重復開啟!");
con = ds.getConnection();//給con賦值,表示開啟了事務
con.setAutoCommit(false);//設置為手動提交
tl.set(con);//把當前事務連接放到tl中
}
/**
* 提交事務
* @throws SQLException
*/
public static void commitTransaction() throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(con == null) throw new SQLException("沒有事務不能提交!");
con.commit();//提交事務
con.close();//關閉連接
con = null;//表示事務結束!
tl.remove();
}
/**
* 回滾事務
* @throws SQLException
*/
public static void rollbackTransaction() throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(con == null) throw new SQLException("沒有事務不能回滾!");
con.rollback();
con.close();
con = null;
tl.remove();
}
/**
* 釋放Connection
* @param con
* @throws SQLException
*/
public static void releaseConnection(Connection connection) throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(connection != con) {//如果參數連接,與當前事務連接不同,說明這個連接不是當前事務,可以關閉!
if(connection != null &&!connection.isClosed()) {//如果參數連接沒有關閉,關閉之!
connection.close();
}
}
}
}