JavaWeb中JdbcUtils的实现:使用事务

 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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值