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.ResultSet; 025import java.sql.SQLException; 026 027import javax.sql.DataSource; 028 029import org.apache.commons.logging.Log; 030import org.apache.commons.logging.LogFactory; 031 032import org.springframework.core.Constants; 033import org.springframework.lang.Nullable; 034 035/** 036 * Proxy for a target DataSource, fetching actual JDBC Connections lazily, 037 * i.e. not until first creation of a Statement. Connection initialization 038 * properties like auto-commit mode, transaction isolation and read-only mode 039 * will be kept and applied to the actual JDBC Connection as soon as an 040 * actual Connection is fetched (if ever). Consequently, commit and rollback 041 * calls will be ignored if no Statements have been created. 042 * 043 * <p>This DataSource proxy allows to avoid fetching JDBC Connections from 044 * a pool unless actually necessary. JDBC transaction control can happen 045 * without fetching a Connection from the pool or communicating with the 046 * database; this will be done lazily on first creation of a JDBC Statement. 047 * 048 * <p><b>If you configure both a LazyConnectionDataSourceProxy and a 049 * TransactionAwareDataSourceProxy, make sure that the latter is the outermost 050 * DataSource.</b> In such a scenario, data access code will talk to the 051 * transaction-aware DataSource, which will in turn work with the 052 * LazyConnectionDataSourceProxy. 053 * 054 * <p>Lazy fetching of physical JDBC Connections is particularly beneficial 055 * in a generic transaction demarcation environment. It allows you to demarcate 056 * transactions on all methods that could potentially perform data access, 057 * without paying a performance penalty if no actual data access happens. 058 * 059 * <p>This DataSource proxy gives you behavior analogous to JTA and a 060 * transactional JNDI DataSource (as provided by the Java EE server), even 061 * with a local transaction strategy like DataSourceTransactionManager or 062 * HibernateTransactionManager. It does not add value with Spring's 063 * JtaTransactionManager as transaction strategy. 064 * 065 * <p>Lazy fetching of JDBC Connections is also recommended for read-only 066 * operations with Hibernate, in particular if the chances of resolving the 067 * result in the second-level cache are high. This avoids the need to 068 * communicate with the database at all for such read-only operations. 069 * You will get the same effect with non-transactional reads, but lazy fetching 070 * of JDBC Connections allows you to still perform reads in transactions. 071 * 072 * <p><b>NOTE:</b> This DataSource proxy needs to return wrapped Connections 073 * (which implement the {@link ConnectionProxy} interface) in order to handle 074 * lazy fetching of an actual JDBC Connection. Use {@link Connection#unwrap} 075 * 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 @Nullable 089 private Boolean defaultAutoCommit; 090 091 @Nullable 092 private Integer defaultTransactionIsolation; 093 094 095 /** 096 * Create a new LazyConnectionDataSourceProxy. 097 * @see #setTargetDataSource 098 */ 099 public LazyConnectionDataSourceProxy() { 100 } 101 102 /** 103 * Create a new LazyConnectionDataSourceProxy. 104 * @param targetDataSource the target DataSource 105 */ 106 public LazyConnectionDataSourceProxy(DataSource targetDataSource) { 107 setTargetDataSource(targetDataSource); 108 afterPropertiesSet(); 109 } 110 111 112 /** 113 * Set the default auto-commit mode to expose when no target Connection 114 * has been fetched yet (-> actual JDBC Connection default not known yet). 115 * <p>If not specified, the default gets determined by checking a target 116 * Connection on startup. If that check fails, the default will be determined 117 * lazily on first access of a Connection. 118 * @see java.sql.Connection#setAutoCommit 119 */ 120 public void setDefaultAutoCommit(boolean defaultAutoCommit) { 121 this.defaultAutoCommit = defaultAutoCommit; 122 } 123 124 /** 125 * Set the default transaction isolation level to expose when no target Connection 126 * has been fetched yet (-> actual JDBC Connection default not known yet). 127 * <p>This property accepts the int constant value (e.g. 8) as defined in the 128 * {@link java.sql.Connection} interface; it is mainly intended for programmatic 129 * use. Consider using the "defaultTransactionIsolationName" property for setting 130 * the value by name (e.g. "TRANSACTION_SERIALIZABLE"). 131 * <p>If not specified, the default gets determined by checking a target 132 * Connection on startup. If that check fails, the default will be determined 133 * lazily on first access of a Connection. 134 * @see #setDefaultTransactionIsolationName 135 * @see java.sql.Connection#setTransactionIsolation 136 */ 137 public void setDefaultTransactionIsolation(int defaultTransactionIsolation) { 138 this.defaultTransactionIsolation = defaultTransactionIsolation; 139 } 140 141 /** 142 * Set the default transaction isolation level by the name of the corresponding 143 * constant in {@link java.sql.Connection}, e.g. "TRANSACTION_SERIALIZABLE". 144 * @param constantName name of the constant 145 * @see #setDefaultTransactionIsolation 146 * @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED 147 * @see java.sql.Connection#TRANSACTION_READ_COMMITTED 148 * @see java.sql.Connection#TRANSACTION_REPEATABLE_READ 149 * @see java.sql.Connection#TRANSACTION_SERIALIZABLE 150 */ 151 public void setDefaultTransactionIsolationName(String constantName) { 152 setDefaultTransactionIsolation(constants.asNumber(constantName).intValue()); 153 } 154 155 156 @Override 157 public void afterPropertiesSet() { 158 super.afterPropertiesSet(); 159 160 // Determine default auto-commit and transaction isolation 161 // via a Connection from the target DataSource, if possible. 162 if (this.defaultAutoCommit == null || this.defaultTransactionIsolation == null) { 163 try { 164 try (Connection con = obtainTargetDataSource().getConnection()) { 165 checkDefaultConnectionProperties(con); 166 } 167 } 168 catch (SQLException ex) { 169 logger.debug("Could not retrieve default auto-commit and transaction isolation settings", ex); 170 } 171 } 172 } 173 174 /** 175 * Check the default connection properties (auto-commit, transaction isolation), 176 * keeping them to be able to expose them correctly without fetching an actual 177 * JDBC Connection from the target DataSource. 178 * <p>This will be invoked once on startup, but also for each retrieval of a 179 * target Connection. If the check failed on startup (because the database was 180 * down), we'll lazily retrieve those settings. 181 * @param con the Connection to use for checking 182 * @throws SQLException if thrown by Connection methods 183 */ 184 protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException { 185 if (this.defaultAutoCommit == null) { 186 this.defaultAutoCommit = con.getAutoCommit(); 187 } 188 if (this.defaultTransactionIsolation == null) { 189 this.defaultTransactionIsolation = con.getTransactionIsolation(); 190 } 191 } 192 193 /** 194 * Expose the default auto-commit value. 195 */ 196 @Nullable 197 protected Boolean defaultAutoCommit() { 198 return this.defaultAutoCommit; 199 } 200 201 /** 202 * Expose the default transaction isolation value. 203 */ 204 @Nullable 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 @Nullable 252 private String username; 253 254 @Nullable 255 private String password; 256 257 @Nullable 258 private Boolean autoCommit; 259 260 @Nullable 261 private Integer transactionIsolation; 262 263 private boolean readOnly = false; 264 265 private int holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT; 266 267 private boolean closed = false; 268 269 @Nullable 270 private Connection target; 271 272 public LazyConnectionInvocationHandler() { 273 this.autoCommit = defaultAutoCommit(); 274 this.transactionIsolation = defaultTransactionIsolation(); 275 } 276 277 public LazyConnectionInvocationHandler(String username, String password) { 278 this(); 279 this.username = username; 280 this.password = password; 281 } 282 283 @Override 284 @Nullable 285 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 286 // Invocation on ConnectionProxy interface coming in... 287 288 if (method.getName().equals("equals")) { 289 // We must avoid fetching a target Connection for "equals". 290 // Only consider equal when proxies are identical. 291 return (proxy == args[0]); 292 } 293 else if (method.getName().equals("hashCode")) { 294 // We must avoid fetching a target Connection for "hashCode", 295 // and we must return the same hash code even when the target 296 // Connection has been fetched: use hashCode of Connection proxy. 297 return System.identityHashCode(proxy); 298 } 299 else if (method.getName().equals("unwrap")) { 300 if (((Class<?>) args[0]).isInstance(proxy)) { 301 return proxy; 302 } 303 } 304 else if (method.getName().equals("isWrapperFor")) { 305 if (((Class<?>) args[0]).isInstance(proxy)) { 306 return true; 307 } 308 } 309 else if (method.getName().equals("getTargetConnection")) { 310 // Handle getTargetConnection method: return underlying connection. 311 return getTargetConnection(method); 312 } 313 314 if (!hasTargetConnection()) { 315 // No physical target Connection kept yet -> 316 // resolve transaction demarcation methods without fetching 317 // a physical JDBC Connection until absolutely necessary. 318 319 if (method.getName().equals("toString")) { 320 return "Lazy Connection proxy for target DataSource [" + getTargetDataSource() + "]"; 321 } 322 else if (method.getName().equals("getAutoCommit")) { 323 if (this.autoCommit != null) { 324 return this.autoCommit; 325 } 326 // Else fetch actual Connection and check there, 327 // because we didn't have a default specified. 328 } 329 else if (method.getName().equals("setAutoCommit")) { 330 this.autoCommit = (Boolean) args[0]; 331 return null; 332 } 333 else if (method.getName().equals("getTransactionIsolation")) { 334 if (this.transactionIsolation != null) { 335 return this.transactionIsolation; 336 } 337 // Else fetch actual Connection and check there, 338 // because we didn't have a default specified. 339 } 340 else if (method.getName().equals("setTransactionIsolation")) { 341 this.transactionIsolation = (Integer) args[0]; 342 return null; 343 } 344 else if (method.getName().equals("isReadOnly")) { 345 return this.readOnly; 346 } 347 else if (method.getName().equals("setReadOnly")) { 348 this.readOnly = (Boolean) args[0]; 349 return null; 350 } 351 else if (method.getName().equals("getHoldability")) { 352 return this.holdability; 353 } 354 else if (method.getName().equals("setHoldability")) { 355 this.holdability = (Integer) args[0]; 356 return null; 357 } 358 else if (method.getName().equals("commit") || method.getName().equals("rollback")) { 359 // Ignore: no statements created yet. 360 return null; 361 } 362 else if (method.getName().equals("getWarnings") || method.getName().equals("clearWarnings")) { 363 // Ignore: no warnings to expose yet. 364 return null; 365 } 366 else if (method.getName().equals("close")) { 367 // Ignore: no target connection yet. 368 this.closed = true; 369 return null; 370 } 371 else if (method.getName().equals("isClosed")) { 372 return this.closed; 373 } 374 else if (this.closed) { 375 // Connection proxy closed, without ever having fetched a 376 // physical JDBC Connection: throw corresponding SQLException. 377 throw new SQLException("Illegal operation: connection is closed"); 378 } 379 } 380 381 // Target Connection already fetched, 382 // or target Connection necessary for current operation -> 383 // invoke method on target connection. 384 try { 385 return method.invoke(getTargetConnection(method), args); 386 } 387 catch (InvocationTargetException ex) { 388 throw ex.getTargetException(); 389 } 390 } 391 392 /** 393 * Return whether the proxy currently holds a target Connection. 394 */ 395 private boolean hasTargetConnection() { 396 return (this.target != null); 397 } 398 399 /** 400 * Return the target Connection, fetching it and initializing it if necessary. 401 */ 402 private Connection getTargetConnection(Method operation) throws SQLException { 403 if (this.target == null) { 404 // No target Connection held -> fetch one. 405 if (logger.isTraceEnabled()) { 406 logger.trace("Connecting to database for operation '" + operation.getName() + "'"); 407 } 408 409 // Fetch physical Connection from DataSource. 410 this.target = (this.username != null) ? 411 obtainTargetDataSource().getConnection(this.username, this.password) : 412 obtainTargetDataSource().getConnection(); 413 414 // If we still lack default connection properties, check them now. 415 checkDefaultConnectionProperties(this.target); 416 417 // Apply kept transaction settings, if any. 418 if (this.readOnly) { 419 try { 420 this.target.setReadOnly(true); 421 } 422 catch (Exception ex) { 423 // "read-only not supported" -> ignore, it's just a hint anyway 424 logger.debug("Could not set JDBC Connection read-only", ex); 425 } 426 } 427 if (this.transactionIsolation != null && 428 !this.transactionIsolation.equals(defaultTransactionIsolation())) { 429 this.target.setTransactionIsolation(this.transactionIsolation); 430 } 431 if (this.autoCommit != null && this.autoCommit != this.target.getAutoCommit()) { 432 this.target.setAutoCommit(this.autoCommit); 433 } 434 } 435 436 else { 437 // Target Connection already held -> return it. 438 if (logger.isTraceEnabled()) { 439 logger.trace("Using existing database connection for operation '" + operation.getName() + "'"); 440 } 441 } 442 443 return this.target; 444 } 445 } 446 447}