1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.ibatis.sqlmap.engine.transaction.jdbc;
17
18 import com.ibatis.common.jdbc.logging.ConnectionLogProxy;
19 import com.ibatis.common.logging.Log;
20 import com.ibatis.common.logging.LogFactory;
21 import com.ibatis.sqlmap.engine.transaction.IsolationLevel;
22 import com.ibatis.sqlmap.engine.transaction.Transaction;
23 import com.ibatis.sqlmap.engine.transaction.TransactionException;
24
25 import java.sql.Connection;
26 import java.sql.SQLException;
27
28 import javax.sql.DataSource;
29
30
31
32
33 public class JdbcTransaction implements Transaction {
34
35
36 private static final Log connectionLog = LogFactory.getLog(Connection.class);
37
38
39 private DataSource dataSource;
40
41
42 private Connection connection;
43
44
45 private IsolationLevel isolationLevel = new IsolationLevel();
46
47
48
49
50
51
52
53
54
55
56
57
58 public JdbcTransaction(DataSource ds, int isolationLevel) throws TransactionException {
59
60 dataSource = ds;
61 if (dataSource == null) {
62 throw new TransactionException("JdbcTransaction initialization failed. DataSource was null.");
63 }
64 this.isolationLevel.setIsolationLevel(isolationLevel);
65 }
66
67
68
69
70
71
72
73
74
75 private void init() throws SQLException, TransactionException {
76
77 connection = dataSource.getConnection();
78 if (connection == null) {
79 throw new TransactionException(
80 "JdbcTransaction could not start transaction. Cause: The DataSource returned a null connection.");
81 }
82
83 isolationLevel.applyIsolationLevel(connection);
84
85 if (connection.getAutoCommit()) {
86 connection.setAutoCommit(false);
87 }
88
89 if (connectionLog.isDebugEnabled()) {
90 connection = ConnectionLogProxy.newInstance(connection);
91 }
92 }
93
94 @Override
95 public void commit() throws SQLException, TransactionException {
96 if (connection != null) {
97 connection.commit();
98 }
99 }
100
101 @Override
102 public void rollback() throws SQLException, TransactionException {
103 if (connection != null) {
104 connection.rollback();
105 }
106 }
107
108 @Override
109 public void close() throws SQLException, TransactionException {
110 if (connection != null) {
111 try {
112 isolationLevel.restoreIsolationLevel(connection);
113 } finally {
114 connection.close();
115 connection = null;
116 }
117 }
118 }
119
120 @Override
121 public Connection getConnection() throws SQLException, TransactionException {
122 if (connection == null) {
123 init();
124 }
125 return connection;
126 }
127
128 }