-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataSourceUtils.txt
63 lines (54 loc) · 1.45 KB
/
DataSourceUtils.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package ****;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class MyDataSource {
//获得connection---------从连接池中获取
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//创建ThreadLocal
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
/*
* 开启事务
*/
public static void startTransation() throws SQLException {
Connection conn = getCurrentConnection();
conn.setAutoCommit(false);
}
/*
* 回滚事务
*/
public static void rollBack() throws SQLException {
getCurrentConnection().rollback();
}
/*
* 提交事务
*/
public static void commit() throws SQLException {
Connection conn = getCurrentConnection();
conn.commit();
//提交后将本次connection从ThreadLocal中移除
tl.remove();
conn.close();
}
/*
* 一般方法的增强,利用线程,获得当前线程上绑定的connection
*/
public static Connection getCurrentConnection() throws SQLException {
//先从ThreadLocal中寻找当前线程是否有对应的Connection
Connection conn = tl.get();
//判断conn是否为空
if(conn == null) {
//获得新的connection
conn = getConnection();
//新获得的connection存入ThreadLocal中
tl.set(conn);
}
return conn;
}
/*
* 一般方法
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}