ThreadLocal 内部时map,以当前线程为键。那么每个线程都有自己的值,互不干扰。
必须提供c3p0-copnfig.xml文件
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtils {
/*
* 1.getConnection,判断是否有事务
* 2.开启事务
* 3.提交事务
* 4.回滚事务
* 5.释放con连接
*/
//饿汉式
private static DataSource dataSource=new ComboPooledDataSource();
private static ThreadLocal<Connection> tLocal=new ThreadLocal<Connection>();
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection() throws SQLException{
Connection con=tLocal.get();
if(con!=null) return con;
return dataSource.getConnection();
}
public static void beginTransaction() throws SQLException{
Connection con=tLocal.get();
if(con!=null)
throw new SQLException("事务已经开启了,不能重复开启!");
con=dataSource.getConnection();
con.setAutoCommit(false);
tLocal.set(con);
}
public static void commitTransaction() throws SQLException{
Connection con=tLocal.get();
if(con==null)
throw new SQLException("没有事务,不能提交!");
con.commit();
con.close();
con=null;//表示事务结束
tLocal.remove();
}
public static void rollbackTransaction() throws SQLException{
Connection con=tLocal.get();
if(con==null)
throw new SQLException("没有事务,不能回滚!");
con.rollback();
con.close();
con=null;//表示事务结束
tLocal.remove();
}
public static void releaseTransaction(Connection connection) throws SQLException{
Connection con=tLocal.get();
//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!
if(connection!=con){
if(connection!=null&& !connection.isClosed())
connection.close();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClassName">com.mysql.jdbc.Driver</property>
<property name="Url">jdbc:mysql//localhost:3306/mydb3</property>
<property name="username">root</property>
<property name="password">123</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>