View Javadoc
1   /*
2    *    Copyright 2009-2022 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.transaction.jdbc;
17  
18  import java.sql.Connection;
19  import java.sql.SQLException;
20  
21  import javax.sql.DataSource;
22  
23  import org.apache.ibatis.logging.Log;
24  import org.apache.ibatis.logging.LogFactory;
25  import org.apache.ibatis.session.TransactionIsolationLevel;
26  import org.apache.ibatis.transaction.Transaction;
27  import org.apache.ibatis.transaction.TransactionException;
28  
29  /**
30   * {@link Transaction} that makes use of the JDBC commit and rollback facilities directly.
31   * It relies on the connection retrieved from the dataSource to manage the scope of the transaction.
32   * Delays connection retrieval until getConnection() is called.
33   * Ignores commit or rollback requests when autocommit is on.
34   *
35   * @author Clinton Begin
36   *
37   * @see JdbcTransactionFactory
38   */
39  public class JdbcTransaction implements Transaction {
40  
41    private static final Log log = LogFactory.getLog(JdbcTransaction.class);
42  
43    protected Connection connection;
44    protected DataSource dataSource;
45    protected TransactionIsolationLevel level;
46    protected boolean autoCommit;
47    protected boolean skipSetAutoCommitOnClose;
48  
49    public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
50      this(ds, desiredLevel, desiredAutoCommit, false);
51    }
52  
53    public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit, boolean skipSetAutoCommitOnClose) {
54      dataSource = ds;
55      level = desiredLevel;
56      autoCommit = desiredAutoCommit;
57      this.skipSetAutoCommitOnClose = skipSetAutoCommitOnClose;
58    }
59  
60    public JdbcTransaction(Connection connection) {
61      this.connection = connection;
62    }
63  
64    @Override
65    public Connection getConnection() throws SQLException {
66      if (connection == null) {
67        openConnection();
68      }
69      return connection;
70    }
71  
72    @Override
73    public void commit() throws SQLException {
74      if (connection != null && !connection.getAutoCommit()) {
75        if (log.isDebugEnabled()) {
76          log.debug("Committing JDBC Connection [" + connection + "]");
77        }
78        connection.commit();
79      }
80    }
81  
82    @Override
83    public void rollback() throws SQLException {
84      if (connection != null && !connection.getAutoCommit()) {
85        if (log.isDebugEnabled()) {
86          log.debug("Rolling back JDBC Connection [" + connection + "]");
87        }
88        connection.rollback();
89      }
90    }
91  
92    @Override
93    public void close() throws SQLException {
94      if (connection != null) {
95        resetAutoCommit();
96        if (log.isDebugEnabled()) {
97          log.debug("Closing JDBC Connection [" + connection + "]");
98        }
99        connection.close();
100     }
101   }
102 
103   protected void setDesiredAutoCommit(boolean desiredAutoCommit) {
104     try {
105       if (connection.getAutoCommit() != desiredAutoCommit) {
106         if (log.isDebugEnabled()) {
107           log.debug("Setting autocommit to " + desiredAutoCommit + " on JDBC Connection [" + connection + "]");
108         }
109         connection.setAutoCommit(desiredAutoCommit);
110       }
111     } catch (SQLException e) {
112       // Only a very poorly implemented driver would fail here,
113       // and there's not much we can do about that.
114       throw new TransactionException("Error configuring AutoCommit.  "
115           + "Your driver may not support getAutoCommit() or setAutoCommit(). "
116           + "Requested setting: " + desiredAutoCommit + ".  Cause: " + e, e);
117     }
118   }
119 
120   protected void resetAutoCommit() {
121     try {
122       if (!skipSetAutoCommitOnClose && !connection.getAutoCommit()) {
123         // MyBatis does not call commit/rollback on a connection if just selects were performed.
124         // Some databases start transactions with select statements
125         // and they mandate a commit/rollback before closing the connection.
126         // A workaround is setting the autocommit to true before closing the connection.
127         // Sybase throws an exception here.
128         if (log.isDebugEnabled()) {
129           log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]");
130         }
131         connection.setAutoCommit(true);
132       }
133     } catch (SQLException e) {
134       if (log.isDebugEnabled()) {
135         log.debug("Error resetting autocommit to true "
136             + "before closing the connection.  Cause: " + e);
137       }
138     }
139   }
140 
141   protected void openConnection() throws SQLException {
142     if (log.isDebugEnabled()) {
143       log.debug("Opening JDBC Connection");
144     }
145     connection = dataSource.getConnection();
146     if (level != null) {
147       connection.setTransactionIsolation(level.getLevel());
148     }
149     setDesiredAutoCommit(autoCommit);
150   }
151 
152   @Override
153   public Integer getTimeout() throws SQLException {
154     return null;
155   }
156 
157 }