JdbcUtils工具类3.0最终版,添加了事务相关功能和释放链接。最终版本可以直接打成jar包,在后面的基本项目都会使用该工具类
1. JdbcUtils代码
/**
* 最终版
* @author hui.zhang
*
*/
public class JdbcUtils {
// 配置文件的默认配置,必须给出c3p0-config.xml
private static ComboPooledDataSource dataSource = new ComboPooledDataSource(); //事务专用连接
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
/**
* 使用连接池返回一个连接对象
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection con = tl.get();
//当con比等于null,说明已经开启了事务
if(con != null) return con;
return dataSource.getConnection();
} /**
* 返回连接池对象
* @return
*/
public static DataSource getDataSource() {
return dataSource;
} /**
* 开启事务
* 1. 获取一个Connection,设置它的setAutoCommit(false)
* 2. 要保证dao中使用的连接是我们刚刚创建的
* @throws SQLException
*/
public static void beginTransaction() throws SQLException{
Connection con = tl.get();
if(con != null) throw new SQLException("已经开启了事务,请不要重复开启!");
con = getConnection();
con.setAutoCommit(false);
tl.set(con);
} /**
* 提交事务
* 1. 获取beginTransaction提供的Connection,然后调用commit方法
* @throws SQLException
*/
public static void commitTransaction() throws SQLException{
Connection con = tl.get();
if(con == null) throw new SQLException("还没有开启事务,不能提交!");
con.commit();
con.close();
tl.remove();
} /**
* 回滚事务
* 1. 获取beginTransaction提供的Connection,然后调用rollback方法
* @throws SQLException
*/
public static void rollbackTransaction() throws SQLException{
Connection con = tl.get();
if(con == null) throw new SQLException("还没有开启事务,不能回滚!");
con.rollback();
con.close();
tl.remove();
} /**
* 释放连接
* @param connection
* @throws SQLException
*/
public static void releaseConnection(Connection connection) throws SQLException{
Connection con = tl.get();
//判断是不是事务专用连接,如果是不用关
if(con == null)
connection.close();
//如果con != null,说明有事务,需要判断参数连接是否与con相同
//不同 说明不是事务专用链接
if(con != connection)
connection.close();
}
}
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再到现在的事务,一步一个脚印。每个版本都应该留下。。。温故而知新!!!