001/*
002 * Copyright 2002-2019 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.jdbc.datasource;
018
019import java.lang.reflect.InvocationHandler;
020import java.lang.reflect.InvocationTargetException;
021import java.lang.reflect.Method;
022import java.lang.reflect.Proxy;
023import java.sql.Connection;
024import java.sql.SQLException;
025import javax.sql.DataSource;
026
027import org.apache.commons.logging.Log;
028import org.apache.commons.logging.LogFactory;
029
030import org.springframework.core.Constants;
031
032/**
033 * Proxy for a target DataSource, fetching actual JDBC Connections lazily,
034 * i.e. not until first creation of a Statement. Connection initialization
035 * properties like auto-commit mode, transaction isolation and read-only mode
036 * will be kept and applied to the actual JDBC Connection as soon as an
037 * actual Connection is fetched (if ever). Consequently, commit and rollback
038 * calls will be ignored if no Statements have been created.
039 *
040 * <p>This DataSource proxy allows to avoid fetching JDBC Connections from
041 * a pool unless actually necessary. JDBC transaction control can happen
042 * without fetching a Connection from the pool or communicating with the
043 * database; this will be done lazily on first creation of a JDBC Statement.
044 *
045 * <p><b>If you configure both a LazyConnectionDataSourceProxy and a
046 * TransactionAwareDataSourceProxy, make sure that the latter is the outermost
047 * DataSource.</b> In such a scenario, data access code will talk to the
048 * transaction-aware DataSource, which will in turn work with the
049 * LazyConnectionDataSourceProxy.
050 *
051 * <p>Lazy fetching of physical JDBC Connections is particularly beneficial
052 * in a generic transaction demarcation environment. It allows you to demarcate
053 * transactions on all methods that could potentially perform data access,
054 * without paying a performance penalty if no actual data access happens.
055 *
056 * <p>This DataSource proxy gives you behavior analogous to JTA and a
057 * transactional JNDI DataSource (as provided by the Java EE server), even
058 * with a local transaction strategy like DataSourceTransactionManager or
059 * HibernateTransactionManager. It does not add value with Spring's
060 * JtaTransactionManager as transaction strategy.
061 *
062 * <p>Lazy fetching of JDBC Connections is also recommended for read-only
063 * operations with Hibernate, in particular if the chances of resolving the
064 * result in the second-level cache are high. This avoids the need to
065 * communicate with the database at all for such read-only operations.
066 * You will get the same effect with non-transactional reads, but lazy fetching
067 * of JDBC Connections allows you to still perform reads in transactions.
068 *
069 * <p><b>NOTE:</b> This DataSource proxy needs to return wrapped Connections
070 * (which implement the {@link ConnectionProxy} interface) in order to handle
071 * lazy fetching of an actual JDBC Connection. Therefore, the returned Connections
072 * cannot be cast to a native JDBC Connection type such as OracleConnection or
073 * to a connection pool implementation type. Use a corresponding
074 * {@link org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor}
075 * or JDBC 4's {@link Connection#unwrap} to retrieve the native JDBC Connection.
076 *
077 * @author Juergen Hoeller
078 * @since 1.1.4
079 * @see DataSourceTransactionManager
080 */
081public class LazyConnectionDataSourceProxy extends DelegatingDataSource {
082
083        /** Constants instance for TransactionDefinition */
084        private static final Constants constants = new Constants(Connection.class);
085
086        private static final Log logger = LogFactory.getLog(LazyConnectionDataSourceProxy.class);
087
088        private Boolean defaultAutoCommit;
089
090        private Integer defaultTransactionIsolation;
091
092
093        /**
094         * Create a new LazyConnectionDataSourceProxy.
095         * @see #setTargetDataSource
096         */
097        public LazyConnectionDataSourceProxy() {
098        }
099
100        /**
101         * Create a new LazyConnectionDataSourceProxy.
102         * @param targetDataSource the target DataSource
103         */
104        public LazyConnectionDataSourceProxy(DataSource targetDataSource) {
105                setTargetDataSource(targetDataSource);
106                afterPropertiesSet();
107        }
108
109
110        /**
111         * Set the default auto-commit mode to expose when no target Connection
112         * has been fetched yet (-> actual JDBC Connection default not known yet).
113         * <p>If not specified, the default gets determined by checking a target
114         * Connection on startup. If that check fails, the default will be determined
115         * lazily on first access of a Connection.
116         * @see java.sql.Connection#setAutoCommit
117         */
118        public void setDefaultAutoCommit(boolean defaultAutoCommit) {
119                this.defaultAutoCommit = defaultAutoCommit;
120        }
121
122        /**
123         * Set the default transaction isolation level to expose when no target Connection
124         * has been fetched yet (-> actual JDBC Connection default not known yet).
125         * <p>This property accepts the int constant value (e.g. 8) as defined in the
126         * {@link java.sql.Connection} interface; it is mainly intended for programmatic
127         * use. Consider using the "defaultTransactionIsolationName" property for setting
128         * the value by name (e.g. "TRANSACTION_SERIALIZABLE").
129         * <p>If not specified, the default gets determined by checking a target
130         * Connection on startup. If that check fails, the default will be determined
131         * lazily on first access of a Connection.
132         * @see #setDefaultTransactionIsolationName
133         * @see java.sql.Connection#setTransactionIsolation
134         */
135        public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
136                this.defaultTransactionIsolation = defaultTransactionIsolation;
137        }
138
139        /**
140         * Set the default transaction isolation level by the name of the corresponding
141         * constant in {@link java.sql.Connection}, e.g. "TRANSACTION_SERIALIZABLE".
142         * @param constantName name of the constant
143         * @see #setDefaultTransactionIsolation
144         * @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED
145         * @see java.sql.Connection#TRANSACTION_READ_COMMITTED
146         * @see java.sql.Connection#TRANSACTION_REPEATABLE_READ
147         * @see java.sql.Connection#TRANSACTION_SERIALIZABLE
148         */
149        public void setDefaultTransactionIsolationName(String constantName) {
150                setDefaultTransactionIsolation(constants.asNumber(constantName).intValue());
151        }
152
153
154        @Override
155        public void afterPropertiesSet() {
156                super.afterPropertiesSet();
157
158                // Determine default auto-commit and transaction isolation
159                // via a Connection from the target DataSource, if possible.
160                if (this.defaultAutoCommit == null || this.defaultTransactionIsolation == null) {
161                        try {
162                                Connection con = getTargetDataSource().getConnection();
163                                try {
164                                        checkDefaultConnectionProperties(con);
165                                }
166                                finally {
167                                        con.close();
168                                }
169                        }
170                        catch (SQLException ex) {
171                                logger.warn("Could not retrieve default auto-commit and transaction isolation settings", ex);
172                        }
173                }
174        }
175
176        /**
177         * Check the default connection properties (auto-commit, transaction isolation),
178         * keeping them to be able to expose them correctly without fetching an actual
179         * JDBC Connection from the target DataSource.
180         * <p>This will be invoked once on startup, but also for each retrieval of a
181         * target Connection. If the check failed on startup (because the database was
182         * down), we'll lazily retrieve those settings.
183         * @param con the Connection to use for checking
184         * @throws SQLException if thrown by Connection methods
185         */
186        protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
187                if (this.defaultAutoCommit == null) {
188                        this.defaultAutoCommit = con.getAutoCommit();
189                }
190                if (this.defaultTransactionIsolation == null) {
191                        this.defaultTransactionIsolation = con.getTransactionIsolation();
192                }
193        }
194
195        /**
196         * Expose the default auto-commit value.
197         */
198        protected Boolean defaultAutoCommit() {
199                return this.defaultAutoCommit;
200        }
201
202        /**
203         * Expose the default transaction isolation value.
204         */
205        protected Integer defaultTransactionIsolation() {
206                return this.defaultTransactionIsolation;
207        }
208
209
210        /**
211         * Return a Connection handle that lazily fetches an actual JDBC Connection
212         * when asked for a Statement (or PreparedStatement or CallableStatement).
213         * <p>The returned Connection handle implements the ConnectionProxy interface,
214         * allowing to retrieve the underlying target Connection.
215         * @return a lazy Connection handle
216         * @see ConnectionProxy#getTargetConnection()
217         */
218        @Override
219        public Connection getConnection() throws SQLException {
220                return (Connection) Proxy.newProxyInstance(
221                                ConnectionProxy.class.getClassLoader(),
222                                new Class<?>[] {ConnectionProxy.class},
223                                new LazyConnectionInvocationHandler());
224        }
225
226        /**
227         * Return a Connection handle that lazily fetches an actual JDBC Connection
228         * when asked for a Statement (or PreparedStatement or CallableStatement).
229         * <p>The returned Connection handle implements the ConnectionProxy interface,
230         * allowing to retrieve the underlying target Connection.
231         * @param username the per-Connection username
232         * @param password the per-Connection password
233         * @return a lazy Connection handle
234         * @see ConnectionProxy#getTargetConnection()
235         */
236        @Override
237        public Connection getConnection(String username, String password) throws SQLException {
238                return (Connection) Proxy.newProxyInstance(
239                                ConnectionProxy.class.getClassLoader(),
240                                new Class<?>[] {ConnectionProxy.class},
241                                new LazyConnectionInvocationHandler(username, password));
242        }
243
244
245        /**
246         * Invocation handler that defers fetching an actual JDBC Connection
247         * until first creation of a Statement.
248         */
249        private class LazyConnectionInvocationHandler implements InvocationHandler {
250
251                private String username;
252
253                private String password;
254
255                private Integer transactionIsolation;
256
257                private Boolean autoCommit;
258
259                private boolean readOnly = false;
260
261                private boolean closed = false;
262
263                private Connection target;
264
265                public LazyConnectionInvocationHandler() {
266                        this.autoCommit = defaultAutoCommit();
267                        this.transactionIsolation = defaultTransactionIsolation();
268                }
269
270                public LazyConnectionInvocationHandler(String username, String password) {
271                        this();
272                        this.username = username;
273                        this.password = password;
274                }
275
276                @Override
277                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
278                        // Invocation on ConnectionProxy interface coming in...
279
280                        if (method.getName().equals("equals")) {
281                                // We must avoid fetching a target Connection for "equals".
282                                // Only consider equal when proxies are identical.
283                                return (proxy == args[0]);
284                        }
285                        else if (method.getName().equals("hashCode")) {
286                                // We must avoid fetching a target Connection for "hashCode",
287                                // and we must return the same hash code even when the target
288                                // Connection has been fetched: use hashCode of Connection proxy.
289                                return System.identityHashCode(proxy);
290                        }
291                        else if (method.getName().equals("unwrap")) {
292                                if (((Class<?>) args[0]).isInstance(proxy)) {
293                                        return proxy;
294                                }
295                        }
296                        else if (method.getName().equals("isWrapperFor")) {
297                                if (((Class<?>) args[0]).isInstance(proxy)) {
298                                        return true;
299                                }
300                        }
301                        else if (method.getName().equals("getTargetConnection")) {
302                                // Handle getTargetConnection method: return underlying connection.
303                                return getTargetConnection(method);
304                        }
305
306                        if (!hasTargetConnection()) {
307                                // No physical target Connection kept yet ->
308                                // resolve transaction demarcation methods without fetching
309                                // a physical JDBC Connection until absolutely necessary.
310
311                                if (method.getName().equals("toString")) {
312                                        return "Lazy Connection proxy for target DataSource [" + getTargetDataSource() + "]";
313                                }
314                                else if (method.getName().equals("getAutoCommit")) {
315                                        if (this.autoCommit != null) {
316                                                return this.autoCommit;
317                                        }
318                                        // Else fetch actual Connection and check there,
319                                        // because we didn't have a default specified.
320                                }
321                                else if (method.getName().equals("setAutoCommit")) {
322                                        this.autoCommit = (Boolean) args[0];
323                                        return null;
324                                }
325                                else if (method.getName().equals("getTransactionIsolation")) {
326                                        if (this.transactionIsolation != null) {
327                                                return this.transactionIsolation;
328                                        }
329                                        // Else fetch actual Connection and check there,
330                                        // because we didn't have a default specified.
331                                }
332                                else if (method.getName().equals("setTransactionIsolation")) {
333                                        this.transactionIsolation = (Integer) args[0];
334                                        return null;
335                                }
336                                else if (method.getName().equals("isReadOnly")) {
337                                        return this.readOnly;
338                                }
339                                else if (method.getName().equals("setReadOnly")) {
340                                        this.readOnly = (Boolean) args[0];
341                                        return null;
342                                }
343                                else if (method.getName().equals("commit") || method.getName().equals("rollback")) {
344                                        // Ignore: no statements created yet.
345                                        return null;
346                                }
347                                else if (method.getName().equals("getWarnings") || method.getName().equals("clearWarnings")) {
348                                        // Ignore: no warnings to expose yet.
349                                        return null;
350                                }
351                                else if (method.getName().equals("close")) {
352                                        // Ignore: no target connection yet.
353                                        this.closed = true;
354                                        return null;
355                                }
356                                else if (method.getName().equals("isClosed")) {
357                                        return this.closed;
358                                }
359                                else if (this.closed) {
360                                        // Connection proxy closed, without ever having fetched a
361                                        // physical JDBC Connection: throw corresponding SQLException.
362                                        throw new SQLException("Illegal operation: connection is closed");
363                                }
364                        }
365
366                        // Target Connection already fetched,
367                        // or target Connection necessary for current operation ->
368                        // invoke method on target connection.
369                        try {
370                                return method.invoke(getTargetConnection(method), args);
371                        }
372                        catch (InvocationTargetException ex) {
373                                throw ex.getTargetException();
374                        }
375                }
376
377                /**
378                 * Return whether the proxy currently holds a target Connection.
379                 */
380                private boolean hasTargetConnection() {
381                        return (this.target != null);
382                }
383
384                /**
385                 * Return the target Connection, fetching it and initializing it if necessary.
386                 */
387                private Connection getTargetConnection(Method operation) throws SQLException {
388                        if (this.target == null) {
389                                // No target Connection held -> fetch one.
390                                if (logger.isDebugEnabled()) {
391                                        logger.debug("Connecting to database for operation '" + operation.getName() + "'");
392                                }
393
394                                // Fetch physical Connection from DataSource.
395                                this.target = (this.username != null) ?
396                                                getTargetDataSource().getConnection(this.username, this.password) :
397                                                getTargetDataSource().getConnection();
398
399                                // If we still lack default connection properties, check them now.
400                                checkDefaultConnectionProperties(this.target);
401
402                                // Apply kept transaction settings, if any.
403                                if (this.readOnly) {
404                                        try {
405                                                this.target.setReadOnly(true);
406                                        }
407                                        catch (Exception ex) {
408                                                // "read-only not supported" -> ignore, it's just a hint anyway
409                                                logger.debug("Could not set JDBC Connection read-only", ex);
410                                        }
411                                }
412                                if (this.transactionIsolation != null &&
413                                                !this.transactionIsolation.equals(defaultTransactionIsolation())) {
414                                        this.target.setTransactionIsolation(this.transactionIsolation);
415                                }
416                                if (this.autoCommit != null && this.autoCommit != this.target.getAutoCommit()) {
417                                        this.target.setAutoCommit(this.autoCommit);
418                                }
419                        }
420
421                        else {
422                                // Target Connection already held -> return it.
423                                if (logger.isDebugEnabled()) {
424                                        logger.debug("Using existing database connection for operation '" + operation.getName() + "'");
425                                }
426                        }
427
428                        return this.target;
429                }
430        }
431
432}