1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.ibatis.sqlmap.engine.transaction.external;
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 ExternalTransaction implements Transaction {
34
35
36 private static final Log connectionLog = LogFactory.getLog(Connection.class);
37
38
39 private DataSource dataSource;
40
41
42 private boolean defaultAutoCommit;
43
44
45 private boolean setAutoCommitAllowed;
46
47
48 private Connection connection;
49
50
51 private IsolationLevel isolationLevel = new IsolationLevel();
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 public ExternalTransaction(DataSource ds, boolean defaultAutoCommit, boolean setAutoCommitAllowed, int isolationLevel)
69 throws TransactionException {
70
71 dataSource = ds;
72 if (dataSource == null) {
73 throw new TransactionException("ExternalTransaction initialization failed. DataSource was null.");
74 }
75
76 this.defaultAutoCommit = defaultAutoCommit;
77 this.setAutoCommitAllowed = setAutoCommitAllowed;
78 this.isolationLevel.setIsolationLevel(isolationLevel);
79 }
80
81
82
83
84
85
86
87
88
89 private void init() throws SQLException, TransactionException {
90
91 connection = dataSource.getConnection();
92 if (connection == null) {
93 throw new TransactionException(
94 "ExternalTransaction could not start transaction. Cause: The DataSource returned a null connection.");
95 }
96
97 isolationLevel.applyIsolationLevel(connection);
98
99 if (setAutoCommitAllowed && connection.getAutoCommit() != defaultAutoCommit) {
100 connection.setAutoCommit(defaultAutoCommit);
101 }
102
103 if (connectionLog.isDebugEnabled()) {
104 connection = ConnectionLogProxy.newInstance(connection);
105 }
106 }
107
108 @Override
109 public void commit() throws SQLException, TransactionException {
110 }
111
112 @Override
113 public void rollback() throws SQLException, TransactionException {
114 }
115
116 @Override
117 public void close() throws SQLException, TransactionException {
118 if (connection != null) {
119 try {
120 isolationLevel.restoreIsolationLevel(connection);
121 } finally {
122 connection.close();
123 connection = null;
124 }
125 }
126 }
127
128 @Override
129 public Connection getConnection() throws SQLException, TransactionException {
130 if (connection == null) {
131 init();
132 }
133 return connection;
134 }
135
136 }