spring-framework / org.springframework.jdbc.datasource

Package org.springframework.jdbc.datasource

Types

AbstractDriverBasedDataSource

abstract class AbstractDriverBasedDataSource : AbstractDataSource

Abstract base class for JDBC javax.sql.DataSource implementations that operate on a JDBC java.sql.Driver.

ConnectionProxy

interface ConnectionProxy : Connection

Subinterface of java.sql.Connection to be implemented by Connection proxies. Allows access to the underlying target Connection.

This interface can be checked when there is a need to cast to a native JDBC Connection such as Oracle's OracleConnection. Alternatively, all such connections also support JDBC 4.0's Connection#unwrap.

DataSourceTransactionManager

open class DataSourceTransactionManager : AbstractPlatformTransactionManager, ResourceTransactionManager, InitializingBean

org.springframework.transaction.PlatformTransactionManager implementation for a single JDBC javax.sql.DataSource. This class is capable of working in any environment with any JDBC driver, as long as the setup uses a javax.sql.DataSource as its Connection factory mechanism. Binds a JDBC Connection from the specified DataSource to the current thread, potentially allowing for one thread-bound Connection per DataSource.

Note: The DataSource that this transaction manager operates on needs to return independent Connections. The Connections may come from a pool (the typical case), but the DataSource must not return thread-scoped / request-scoped Connections or the like. This transaction manager will associate Connections with thread-bound transactions itself, according to the specified propagation behavior. It assumes that a separate, independent Connection can be obtained even during an ongoing transaction.

Application code is required to retrieve the JDBC Connection via DataSourceUtils#getConnection(DataSource) instead of a standard Java EE-style DataSource#getConnection() call. Spring classes such as org.springframework.jdbc.core.JdbcTemplate use this strategy implicitly. If not used in combination with this transaction manager, the DataSourceUtils lookup strategy behaves exactly like the native DataSource lookup; it can thus be used in a portable fashion.

Alternatively, you can allow application code to work with the standard Java EE-style lookup pattern DataSource#getConnection(), for example for legacy code that is not aware of Spring at all. In that case, define a TransactionAwareDataSourceProxy for your target DataSource, and pass that proxy DataSource to your DAOs, which will automatically participate in Spring-managed transactions when accessing it.

Supports custom isolation levels, and timeouts which get applied as appropriate JDBC statement timeouts. To support the latter, application code must either use org.springframework.jdbc.core.JdbcTemplate, call DataSourceUtils#applyTransactionTimeout for each created JDBC Statement, or go through a TransactionAwareDataSourceProxy which will create timeout-aware JDBC Connections and Statements automatically.

Consider defining a LazyConnectionDataSourceProxy for your target DataSource, pointing both this transaction manager and your DAOs to it. This will lead to optimized handling of "empty" transactions, i.e. of transactions without any JDBC statements executed. A LazyConnectionDataSourceProxy will not fetch an actual JDBC Connection from the target DataSource until a Statement gets executed, lazily applying the specified transaction settings to the target Connection.

This transaction manager supports nested transactions via the JDBC 3.0 java.sql.Savepoint mechanism. The "nestedTransactionAllowed" flag defaults to "true", since nested transactions will work without restrictions on JDBC drivers that support savepoints (such as the Oracle JDBC driver).

This transaction manager can be used as a replacement for the org.springframework.transaction.jta.JtaTransactionManager in the single resource case, as it does not require a container that supports JTA, typically in combination with a locally defined JDBC DataSource (e.g. an Apache Commons DBCP connection pool). Switching between this local strategy and a JTA environment is just a matter of configuration!

As of 4.3.4, this transaction manager triggers flush callbacks on registered transaction synchronizations (if synchronization is generally active), assuming resources operating on the underlying JDBC Connection. This allows for setup analogous to JtaTransactionManager, in particular with respect to lazily registered ORM resources (e.g. a Hibernate Session).

DriverManagerDataSource

open class DriverManagerDataSource : AbstractDriverBasedDataSource

Simple implementation of the standard JDBC javax.sql.DataSource interface, configuring the plain old JDBC java.sql.DriverManager via bean properties, and returning a new java.sql.Connection from every getConnection call.

NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.

Useful for test or standalone environments outside of a Java EE container, either as a DataSource bean in a corresponding ApplicationContext or in conjunction with a simple JNDI environment. Pool-assuming Connection.close() calls will simply close the Connection, so any DataSource-aware persistence code should work.

NOTE: Within special class loading environments such as OSGi, this class is effectively superseded by SimpleDriverDataSource due to general class loading issues with the JDBC DriverManager that be resolved through direct Driver usage (which is exactly what SimpleDriverDataSource does).

In a Java EE container, it is recommended to use a JNDI DataSource provided by the container. Such a DataSource can be exposed as a DataSource bean in a Spring ApplicationContext via org.springframework.jndi.JndiObjectFactoryBean, for seamless switching to and from a local DataSource bean like this class. For tests, you can then either set up a mock JNDI environment through Spring's org.springframework.mock.jndi.SimpleNamingContextBuilder, or switch the bean definition to a local DataSource (which is simpler and thus recommended).

If you need a "real" connection pool outside of a Java EE container, consider Apache Commons DBCP or C3P0. Commons DBCP's BasicDataSource and C3P0's ComboPooledDataSource are full connection pool beans, supporting the same basic properties as this class plus specific settings (such as minimal/maximal pool size etc).

IsolationLevelDataSourceAdapter

open class IsolationLevelDataSourceAdapter : UserCredentialsDataSourceAdapter

An adapter for a target javax.sql.DataSource, applying the current Spring transaction's isolation level (and potentially specified user credentials) to every getConnection call. Also applies the read-only flag, if specified.

Can be used to proxy a target JNDI DataSource that does not have the desired isolation level (and user credentials) configured. Client code can work with this DataSource as usual, not worrying about such settings.

Inherits the capability to apply specific user credentials from its superclass UserCredentialsDataSourceAdapter; see the latter's javadoc for details on that functionality (e.g. #setCredentialsForCurrentThread).

WARNING: This adapter simply calls java.sql.Connection#setTransactionIsolation and/or java.sql.Connection#setReadOnly for every Connection obtained from it. It does, however, not reset those settings; it rather expects the target DataSource to perform such resetting as part of its connection pool handling. Make sure that the target DataSource properly cleans up such transaction state.

JdbcTransactionObjectSupport

abstract class JdbcTransactionObjectSupport : SavepointManager, SmartTransactionObject

Convenient base class for JDBC-aware transaction objects. Can contain a ConnectionHolder with a JDBC Connection, and implements the SavepointManager interface based on that ConnectionHolder.

Allows for programmatic management of JDBC java.sql.Savepoint. Spring's org.springframework.transaction.support.DefaultTransactionStatus automatically delegates to this, as it autodetects transaction objects which implement the SavepointManager interface.

LazyConnectionDataSourceProxy

open class LazyConnectionDataSourceProxy : DelegatingDataSource

Proxy for a target DataSource, fetching actual JDBC Connections lazily, i.e. not until first creation of a Statement. Connection initialization properties like auto-commit mode, transaction isolation and read-only mode will be kept and applied to the actual JDBC Connection as soon as an actual Connection is fetched (if ever). Consequently, commit and rollback calls will be ignored if no Statements have been created.

This DataSource proxy allows to avoid fetching JDBC Connections from a pool unless actually necessary. JDBC transaction control can happen without fetching a Connection from the pool or communicating with the database; this will be done lazily on first creation of a JDBC Statement.

If you configure both a LazyConnectionDataSourceProxy and a TransactionAwareDataSourceProxy, make sure that the latter is the outermost DataSource. In such a scenario, data access code will talk to the transaction-aware DataSource, which will in turn work with the LazyConnectionDataSourceProxy.

Lazy fetching of physical JDBC Connections is particularly beneficial in a generic transaction demarcation environment. It allows you to demarcate transactions on all methods that could potentially perform data access, without paying a performance penalty if no actual data access happens.

This DataSource proxy gives you behavior analogous to JTA and a transactional JNDI DataSource (as provided by the Java EE server), even with a local transaction strategy like DataSourceTransactionManager or HibernateTransactionManager. It does not add value with Spring's JtaTransactionManager as transaction strategy.

Lazy fetching of JDBC Connections is also recommended for read-only operations with Hibernate, in particular if the chances of resolving the result in the second-level cache are high. This avoids the need to communicate with the database at all for such read-only operations. You will get the same effect with non-transactional reads, but lazy fetching of JDBC Connections allows you to still perform reads in transactions.

NOTE: This DataSource proxy needs to return wrapped Connections (which implement the ConnectionProxy interface) in order to handle lazy fetching of an actual JDBC Connection. Use Connection#unwrap to retrieve the native JDBC Connection.

SimpleConnectionHandle

open class SimpleConnectionHandle : ConnectionHandle

Simple implementation of the ConnectionHandle interface, containing a given JDBC Connection.

SimpleDriverDataSource

open class SimpleDriverDataSource : AbstractDriverBasedDataSource

Simple implementation of the standard JDBC javax.sql.DataSource interface, configuring a plain old JDBC java.sql.Driver via bean properties, and returning a new java.sql.Connection from every getConnection call.

NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.

In a Java EE container, it is recommended to use a JNDI DataSource provided by the container. Such a DataSource can be exposed as a DataSource bean in a Spring ApplicationContext via org.springframework.jndi.JndiObjectFactoryBean, for seamless switching to and from a local DataSource bean like this class.

If you need a "real" connection pool outside of a Java EE container, consider Apache Commons DBCP or C3P0. Commons DBCP's BasicDataSource and C3P0's ComboPooledDataSource are full connection pool beans, supporting the same basic properties as this class plus specific settings (such as minimal/maximal pool size etc).

SingleConnectionDataSource

open class SingleConnectionDataSource : DriverManagerDataSource, SmartDataSource, DisposableBean

Implementation of SmartDataSource that wraps a single JDBC Connection which is not closed after use. Obviously, this is not multi-threading capable.

Note that at shutdown, someone should close the underlying Connection via the close() method. Client code will never call close on the Connection handle if it is SmartDataSource-aware (e.g. uses DataSourceUtils.releaseConnection).

If client code will call close() in the assumption of a pooled Connection, like when using persistence tools, set "suppressClose" to "true". This will return a close-suppressing proxy instead of the physical Connection.

This is primarily intended for testing. For example, it enables easy testing outside an application server, for code that expects to work on a DataSource. In contrast to DriverManagerDataSource, it reuses the same Connection all the time, avoiding excessive creation of physical Connections.

TransactionAwareDataSourceProxy

open class TransactionAwareDataSourceProxy : DelegatingDataSource

Proxy for a target JDBC javax.sql.DataSource, adding awareness of Spring-managed transactions. Similar to a transactional JNDI DataSource as provided by a Java EE server.

Data access code that should remain unaware of Spring's data access support can work with this proxy to seamlessly participate in Spring-managed transactions. Note that the transaction manager, for example DataSourceTransactionManager, still needs to work with the underlying DataSource, not with this proxy.

Make sure that TransactionAwareDataSourceProxy is the outermost DataSource of a chain of DataSource proxies/adapters. TransactionAwareDataSourceProxy can delegate either directly to the target connection pool or to some intermediary proxy/adapter like LazyConnectionDataSourceProxy or UserCredentialsDataSourceAdapter.

Delegates to DataSourceUtils for automatically participating in thread-bound transactions, for example managed by DataSourceTransactionManager. getConnection calls and close calls on returned Connections will behave properly within a transaction, i.e. always operate on the transactional Connection. If not within a transaction, normal DataSource behavior applies.

This proxy allows data access code to work with the plain JDBC API and still participate in Spring-managed transactions, similar to JDBC code in a Java EE/JTA environment. However, if possible, use Spring's DataSourceUtils, JdbcTemplate or JDBC operation objects to get transaction participation even without a proxy for the target DataSource, avoiding the need to define such a proxy in the first place.

As a further effect, using a transaction-aware DataSource will apply remaining transaction timeouts to all created JDBC (Prepared/Callable)Statement. This means that all operations performed through standard JDBC will automatically participate in Spring-managed transaction timeouts.

NOTE: This DataSource proxy needs to return wrapped Connections (which implement the ConnectionProxy interface) in order to handle close calls properly. Use Connection#unwrap to retrieve the native JDBC Connection.

WebSphereDataSourceAdapter

open class WebSphereDataSourceAdapter : IsolationLevelDataSourceAdapter

DataSource implementation that delegates all calls to a WebSphere target DataSource, typically obtained from JNDI, applying a current isolation level and/or current user credentials to every Connection obtained from it.

Uses IBM-specific API to get a JDBC Connection with a specific isolation level (and read-only flag) from a WebSphere DataSource (IBM code example). Supports the transaction-specific isolation level exposed by org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionIsolationLevel(). It's also possible to specify a default isolation level, to be applied when the current Spring-managed transaction does not define a specific isolation level.

Usage example, defining the target DataSource as an inner-bean JNDI lookup (of course, you can link to any WebSphere DataSource through a bean reference):

 <bean id="myDataSource" class="org.springframework.jdbc.datasource.WebSphereDataSourceAdapter"> <property name="targetDataSource"> <bean class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="jdbc/myds"/> </bean> </property> </bean>
Thanks to Ricardo Olivieri for submitting the original implementation of this approach!