一、在JDBC连接中开启事务,调用完成后关闭连接(传统方式不推荐使用)
private static DataSource ds;
static{
try{
Properties prop = new Properties();
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
prop.load(in);
BasicDataSourceFactory factory = new BasicDataSourceFactory();
ds = factory.createDataSource(prop);
}catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public void transfer() throws SQLException{
Connection conn = null;
try{
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false);
//对数据进行操作
conn.commit();
}finally{
if(conn!=null) conn.close();
}
}
二、用ThreadLocal类在线程上绑定一个连接
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
在获得连接的时候就绑定到threadLocal 上
public static Connection getConnection() throws SQLException{
try{
//得到当前线程上绑定的连接
Connection conn = threadLocal.get();
if(conn==null){ //代表线程上没有绑定连接
conn = ds.getConnection();
threadLocal.set(conn);
}
return conn;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
然后开启事务
public static void startTransaction(){
try{
//得到当前线程上绑定连接开启事务
Connection conn = threadLocal.get();
if(conn==null){ //代表线程上没有绑定连接
conn = ds.getConnection();
threadLocal.set(conn);
}
conn.setAutoCommit(false);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
执行完相应操作后提交事务
public static void commitTransaction(){
try{
Connection conn = threadLocal.get();
if(conn!=null){
conn.commit();
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}
最后关闭连接
public static void closeConnection(){
try{
Connection conn = threadLocal.get();
if(conn!=null){
conn.close();
}
}catch (Exception e) {
throw new RuntimeException(e);
}finally{
//千万注意,解除当前线程上绑定的链接(从threadlocal容器中移除对应当前线程的链接)
threadLocal.remove();
}
}
第三种方法是用spring中的事务管理器,本次不做讨论