View Javadoc
1   /*
2    *    Copyright 2009-2023 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    *       https://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. It relies on the connection
31   * retrieved from the dataSource to manage the scope of the transaction. Delays connection retrieval until
32   * getConnection() is called. Ignores commit or rollback requests when autocommit is on.
33   *
34   * @author Clinton Begin
35   *
36   * @see JdbcTransactionFactory
37   */
38  public class JdbcTransaction implements Transaction {
39  
40    private static final Log log = LogFactory.getLog(JdbcTransaction.class);
41  
42    protected Connection connection;
43    protected DataSource dataSource;
44    protected TransactionIsolationLevel level;
45    protected boolean autoCommit;
46    protected boolean skipSetAutoCommitOnClose;
47  
48    public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
49      this(ds, desiredLevel, desiredAutoCommit, false);
50    }
51  
52    public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit,
53        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(
115           "Error configuring AutoCommit.  " + "Your driver may not support getAutoCommit() or setAutoCommit(). "
116               + "Requested setting: " + desiredAutoCommit + ".  Cause: " + e,
117           e);
118     }
119   }
120 
121   protected void resetAutoCommit() {
122     try {
123       if (!skipSetAutoCommitOnClose && !connection.getAutoCommit()) {
124         // MyBatis does not call commit/rollback on a connection if just selects were performed.
125         // Some databases start transactions with select statements
126         // and they mandate a commit/rollback before closing the connection.
127         // A workaround is setting the autocommit to true before closing the connection.
128         // Sybase throws an exception here.
129         if (log.isDebugEnabled()) {
130           log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]");
131         }
132         connection.setAutoCommit(true);
133       }
134     } catch (SQLException e) {
135       if (log.isDebugEnabled()) {
136         log.debug("Error resetting autocommit to true " + "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 }