Class BasicDataSource
- All Implemented Interfaces:
Wrapper, CommonDataSource, DataSource
- Direct Known Subclasses:
BasicManagedDataSource
Basic implementation of javax.sql.DataSource that is
configured via JavaBeans properties. This is not the only way to
combine the commons-dbcp and commons-pool packages,
but provides a "one stop shopping" solution for basic requirements.
Users extending this class should take care to use appropriate accessors rather than accessing protected fields directly to ensure thread-safety.
- Version:
- $Revision: 895844 $ $Date: 2010-01-04 20:50:04 -0500 (Mon, 04 Jan 2010) $
- Author:
- Glenn L. Nielsen, Craig R. McClanahan, Dirk Verbeeck
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddConnectionProperty(String name, String value) Add a custom connection property to the set that will be passed to our JDBC driver.voidclose()Closes and releases all idle connections that are currently stored in the connection pool associated with this data source.Create (if necessary) and return a connection to the database.getConnection(String user, String pass) BasicDataSource does NOT support this method.Returns the list of SQL statements executed when a physical connection is first created.booleanReturns the default auto-commit property.Returns the default catalog.booleanReturns the default readOnly property.intReturns the default transaction isolation state of returned connections.Returns the class loader specified for loading the JDBC driver.Returns the jdbc driver class name.intReturns the initial size of the connection pool.booleanFlag to log stack traces for application code which abandoned a Statement or Connection.intBasicDataSource does NOT support this method.Returns the log writer being used by this data source.intReturns the maximum number of active connections that can be allocated at the same time.intReturns the maximum number of connections that can remain idle in the pool.intGets the value of themaxOpenPreparedStatementsproperty.longReturns the maximum number of milliseconds that the pool will wait for a connection to be returned before throwing an exception.longReturns theminEvictableIdleTimeMillisproperty.intReturns the minimum number of idle connections in the poolint[Read Only] The current number of active connections that have been allocated from this data source.int[Read Only] The current number of idle connections that are waiting to be allocated from this data source.intReturns the value of thenumTestsPerEvictionRunproperty.Returns the password passed to the JDBC driver to establish connections.booleanFlag to remove abandoned connections if they exceed the removeAbandonedTimout.intTimeout in seconds before an abandoned connection can be removed.booleanReturns thetestOnBorrowproperty.booleanReturns the value of thetestOnReturnproperty.booleanReturns the value of thetestWhileIdleproperty.longReturns the value of thetimeBetweenEvictionRunsMillisproperty.getUrl()Returns the JDBC connectionurlproperty.Returns the JDBC connectionusernameproperty.Returns the validation query used to validate connections before returning them.intReturns the validation query timeout.booleanReturns the value of the accessToUnderlyingConnectionAllowed property.booleanisClosed()If true, this data source is closed and no more connections can be retrieved from this datasource.booleanReturns true if we are pooling statements.booleanisWrapperFor(Class<?> iface) voidRemove a custom connection property.voidsetAccessToUnderlyingConnectionAllowed(boolean allow) Sets the value of the accessToUnderlyingConnectionAllowed property.voidsetConnectionInitSqls(Collection connectionInitSqls) Sets the list of SQL statements to be executed when a physical connection is first created.voidsetConnectionProperties(String connectionProperties) Sets the connection properties passed to driver.connect(...).voidsetDefaultAutoCommit(boolean defaultAutoCommit) Sets default auto-commit state of connections returned by this datasource.voidsetDefaultCatalog(String defaultCatalog) Sets the default catalog.voidsetDefaultReadOnly(boolean defaultReadOnly) Sets defaultReadonly property.voidsetDefaultTransactionIsolation(int defaultTransactionIsolation) Sets the default transaction isolation state for returned connections.voidsetDriverClassLoader(ClassLoader driverClassLoader) Sets the class loader to be used to load the JDBC driver.voidsetDriverClassName(String driverClassName) Sets the jdbc driver class name.voidsetInitialSize(int initialSize) Sets the initial size of the connection pool.voidsetLogAbandoned(boolean logAbandoned) voidsetLoginTimeout(int loginTimeout) BasicDataSource does NOT support this method.voidsetLogWriter(PrintWriter logWriter) Sets the log writer being used by this data source.voidsetMaxActive(int maxActive) Sets the maximum number of active connections that can be allocated at the same time.voidsetMaxIdle(int maxIdle) Sets the maximum number of connections that can remain idle in the pool.voidsetMaxOpenPreparedStatements(int maxOpenStatements) Sets the value of themaxOpenPreparedStatementsproperty.voidsetMaxWait(long maxWait) Sets the maxWait property.voidsetMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) Sets theminEvictableIdleTimeMillisproperty.voidsetMinIdle(int minIdle) Sets the minimum number of idle connections in the pool.voidsetNumTestsPerEvictionRun(int numTestsPerEvictionRun) Sets the value of thenumTestsPerEvictionRunproperty.voidsetPassword(String password) Sets thepassword.voidsetPoolPreparedStatements(boolean poolingStatements) Sets whether to pool statements or not.voidsetRemoveAbandoned(boolean removeAbandoned) voidsetRemoveAbandonedTimeout(int removeAbandonedTimeout) voidsetTestOnBorrow(boolean testOnBorrow) Sets thetestOnBorrowproperty.voidsetTestOnReturn(boolean testOnReturn) Sets thetestOnReturnproperty.voidsetTestWhileIdle(boolean testWhileIdle) Sets thetestWhileIdleproperty.voidsetTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) Sets thetimeBetweenEvictionRunsMillisproperty.voidSets theurl.voidsetUsername(String username) Sets theusername.voidsetValidationQuery(String validationQuery) Sets thevalidationQuery.voidsetValidationQueryTimeout(int timeout) Sets the validation query timeout, the amount of time, in seconds, that connection validation will wait for a response from the database when executing a validation query.<T> TMethods inherited from class Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface CommonDataSource
createShardingKeyBuilderMethods inherited from interface DataSource
createConnectionBuilder
-
Constructor Details
-
BasicDataSource
public BasicDataSource()
-
-
Method Details
-
getDefaultAutoCommit
public boolean getDefaultAutoCommit()Returns the default auto-commit property.- Returns:
- true if default auto-commit is enabled
-
setDefaultAutoCommit
public void setDefaultAutoCommit(boolean defaultAutoCommit) Sets default auto-commit state of connections returned by this datasource.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
defaultAutoCommit- default auto-commit value
-
getDefaultReadOnly
public boolean getDefaultReadOnly()Returns the default readOnly property.- Returns:
- true if connections are readOnly by default
-
setDefaultReadOnly
public void setDefaultReadOnly(boolean defaultReadOnly) Sets defaultReadonly property.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
defaultReadOnly- default read-only value
-
getDefaultTransactionIsolation
public int getDefaultTransactionIsolation()Returns the default transaction isolation state of returned connections.- Returns:
- the default value for transaction isolation state
- See Also:
-
setDefaultTransactionIsolation
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) Sets the default transaction isolation state for returned connections.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
defaultTransactionIsolation- the default transaction isolation state- See Also:
-
getDefaultCatalog
-
setDefaultCatalog
Sets the default catalog.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
defaultCatalog- the default catalog
-
getDriverClassName
Returns the jdbc driver class name.- Returns:
- the jdbc driver class name
-
setDriverClassName
Sets the jdbc driver class name.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
driverClassName- the class name of the jdbc driver
-
getDriverClassLoader
Returns the class loader specified for loading the JDBC driver. Returnsnullif no class loader has been explicitly specified. -
setDriverClassLoader
Sets the class loader to be used to load the JDBC driver.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
driverClassLoader- the class loader with which to load the JDBC driver
-
getMaxActive
public int getMaxActive()Returns the maximum number of active connections that can be allocated at the same time.
A negative number means that there is no limit.
- Returns:
- the maximum number of active connections
-
setMaxActive
public void setMaxActive(int maxActive) Sets the maximum number of active connections that can be allocated at the same time. Use a negative value for no limit.- Parameters:
maxActive- the new value for maxActive- See Also:
-
getMaxIdle
public int getMaxIdle()Returns the maximum number of connections that can remain idle in the pool.
A negative value indicates that there is no limit
- Returns:
- the maximum number of idle connections
-
setMaxIdle
public void setMaxIdle(int maxIdle) Sets the maximum number of connections that can remain idle in the pool.- Parameters:
maxIdle- the new value for maxIdle- See Also:
-
getMinIdle
public int getMinIdle()Returns the minimum number of idle connections in the pool- Returns:
- the minimum number of idle connections
- See Also:
-
setMinIdle
public void setMinIdle(int minIdle) Sets the minimum number of idle connections in the pool.- Parameters:
minIdle- the new value for minIdle- See Also:
-
getInitialSize
public int getInitialSize()Returns the initial size of the connection pool.- Returns:
- the number of connections created when the pool is initialized
-
setInitialSize
public void setInitialSize(int initialSize) Sets the initial size of the connection pool.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
initialSize- the number of connections created when the pool is initialized
-
getMaxWait
public long getMaxWait()Returns the maximum number of milliseconds that the pool will wait for a connection to be returned before throwing an exception.
A value less than or equal to zero means the pool is set to wait indefinitely.
- Returns:
- the maxWait property value
-
setMaxWait
public void setMaxWait(long maxWait) Sets the maxWait property.
Use -1 to make the pool wait indefinitely.
- Parameters:
maxWait- the new value for maxWait- See Also:
-
isPoolPreparedStatements
public boolean isPoolPreparedStatements()Returns true if we are pooling statements.- Returns:
- true if prepared and callable statements are pooled
-
setPoolPreparedStatements
public void setPoolPreparedStatements(boolean poolingStatements) Sets whether to pool statements or not.
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
poolingStatements- pooling on or off
-
getMaxOpenPreparedStatements
public int getMaxOpenPreparedStatements()Gets the value of themaxOpenPreparedStatementsproperty.- Returns:
- the maximum number of open statements
- See Also:
-
setMaxOpenPreparedStatements
public void setMaxOpenPreparedStatements(int maxOpenStatements) Sets the value of the
maxOpenPreparedStatementsproperty.Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
maxOpenStatements- the new maximum number of prepared statements- See Also:
-
getTestOnBorrow
public boolean getTestOnBorrow()Returns thetestOnBorrowproperty.- Returns:
- true if objects are validated before being borrowed from the pool
- See Also:
-
setTestOnBorrow
public void setTestOnBorrow(boolean testOnBorrow) Sets thetestOnBorrowproperty. This property determines whether or not the pool will validate objects before they are borrowed from the pool. For atruevalue to have any effect, thevalidationQueryproperty must be set to a non-null string.- Parameters:
testOnBorrow- new value for testOnBorrow property
-
getTestOnReturn
public boolean getTestOnReturn()Returns the value of thetestOnReturnproperty.- Returns:
- true if objects are validated before being returned to the pool
- See Also:
-
setTestOnReturn
public void setTestOnReturn(boolean testOnReturn) Sets thetestOnReturnproperty. This property determines whether or not the pool will validate objects before they are returned to the pool. For atruevalue to have any effect, thevalidationQueryproperty must be set to a non-null string.- Parameters:
testOnReturn- new value for testOnReturn property
-
getTimeBetweenEvictionRunsMillis
public long getTimeBetweenEvictionRunsMillis()Returns the value of thetimeBetweenEvictionRunsMillisproperty.- Returns:
- the time (in miliseconds) between evictor runs
- See Also:
-
setTimeBetweenEvictionRunsMillis
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) Sets thetimeBetweenEvictionRunsMillisproperty.- Parameters:
timeBetweenEvictionRunsMillis- the new time between evictor runs- See Also:
-
getNumTestsPerEvictionRun
public int getNumTestsPerEvictionRun()Returns the value of thenumTestsPerEvictionRunproperty.- Returns:
- the number of objects to examine during idle object evictor runs
- See Also:
-
setNumTestsPerEvictionRun
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) Sets the value of thenumTestsPerEvictionRunproperty.- Parameters:
numTestsPerEvictionRun- the newnumTestsPerEvictionRunvalue- See Also:
-
getMinEvictableIdleTimeMillis
public long getMinEvictableIdleTimeMillis()Returns theminEvictableIdleTimeMillisproperty.- Returns:
- the value of the
minEvictableIdleTimeMillisproperty - See Also:
-
setMinEvictableIdleTimeMillis
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) Sets theminEvictableIdleTimeMillisproperty.- Parameters:
minEvictableIdleTimeMillis- the minimum amount of time an object may sit idle in the pool- See Also:
-
getTestWhileIdle
public boolean getTestWhileIdle()Returns the value of thetestWhileIdleproperty.- Returns:
- true if objects examined by the idle object evictor are validated
- See Also:
-
setTestWhileIdle
public void setTestWhileIdle(boolean testWhileIdle) Sets thetestWhileIdleproperty. This property determines whether or not the idle object evictor will validate connections. For atruevalue to have any effect, thevalidationQueryproperty must be set to a non-null string.- Parameters:
testWhileIdle- new value for testWhileIdle property
-
getNumActive
public int getNumActive()[Read Only] The current number of active connections that have been allocated from this data source.- Returns:
- the current number of active connections
-
getNumIdle
public int getNumIdle()[Read Only] The current number of idle connections that are waiting to be allocated from this data source.- Returns:
- the current number of idle connections
-
getPassword
Returns the password passed to the JDBC driver to establish connections.- Returns:
- the connection password
-
setPassword
Sets the
password.Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
password- new value for the password
-
getUrl
Returns the JDBC connectionurlproperty.- Returns:
- the
urlpassed to the JDBC driver to establish connections
-
setUrl
Sets the
url.Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
url- the new value for the JDBC connection url
-
getUsername
Returns the JDBC connectionusernameproperty.- Returns:
- the
usernamepassed to the JDBC driver to establish connections
-
setUsername
Sets the
username.Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
username- the new value for the JDBC connection username
-
getValidationQuery
Returns the validation query used to validate connections before returning them.- Returns:
- the SQL validation query
- See Also:
-
setValidationQuery
Sets the
validationQuery.Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
validationQuery- the new value for the validation query
-
getValidationQueryTimeout
public int getValidationQueryTimeout()Returns the validation query timeout.- Returns:
- the timeout in seconds before connection validation queries fail.
- Since:
- 1.3
-
setValidationQueryTimeout
public void setValidationQueryTimeout(int timeout) Sets the validation query timeout, the amount of time, in seconds, that connection validation will wait for a response from the database when executing a validation query. Use a value less than or equal to 0 for no timeout.Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
timeout- new validation query timeout value in seconds- Since:
- 1.3
-
getConnectionInitSqls
Returns the list of SQL statements executed when a physical connection is first created. Returns an empty list if there are no initialization statements configured.- Returns:
- initialization SQL statements
- Since:
- 1.3
-
setConnectionInitSqls
Sets the list of SQL statements to be executed when a physical connection is first created.Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
connectionInitSqls- Collection of SQL statements to execute on connection creation
-
isAccessToUnderlyingConnectionAllowed
public boolean isAccessToUnderlyingConnectionAllowed()Returns the value of the accessToUnderlyingConnectionAllowed property.- Returns:
- true if access to the underlying connection is allowed, false otherwise.
-
setAccessToUnderlyingConnectionAllowed
public void setAccessToUnderlyingConnectionAllowed(boolean allow) Sets the value of the accessToUnderlyingConnectionAllowed property. It controls if the PoolGuard allows access to the underlying connection. (Default: false)
Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is invoked:
getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.- Parameters:
allow- Access to the underlying connection is granted when true.
-
getConnection
Create (if necessary) and return a connection to the database.- Specified by:
getConnectionin interfaceDataSource- Returns:
- a database connection
- Throws:
SQLException- if a database access error occurs
-
getConnection
BasicDataSource does NOT support this method.- Specified by:
getConnectionin interfaceDataSource- Parameters:
user- Database user on whose behalf the Connection is being madepass- The database user's password- Returns:
- nothing - always throws UnsupportedOperationException
- Throws:
UnsupportedOperationExceptionSQLException- if a database access error occurs
-
getLoginTimeout
BasicDataSource does NOT support this method.Returns the login timeout (in seconds) for connecting to the database.
Calls
createDataSource(), so has the side effect of initializing the connection pool.- Specified by:
getLoginTimeoutin interfaceCommonDataSource- Specified by:
getLoginTimeoutin interfaceDataSource- Returns:
- login timeout in seconds
- Throws:
SQLException- if a database access error occursUnsupportedOperationException- If the DataSource implementation does not support the login timeout feature.
-
getLogWriter
Returns the log writer being used by this data source.
Calls
createDataSource(), so has the side effect of initializing the connection pool.- Specified by:
getLogWriterin interfaceCommonDataSource- Specified by:
getLogWriterin interfaceDataSource- Returns:
- log writer in use
- Throws:
SQLException- if a database access error occurs
-
setLoginTimeout
BasicDataSource does NOT support this method.Set the login timeout (in seconds) for connecting to the database.
Calls
createDataSource(), so has the side effect of initializing the connection pool.- Specified by:
setLoginTimeoutin interfaceCommonDataSource- Specified by:
setLoginTimeoutin interfaceDataSource- Parameters:
loginTimeout- The new login timeout, or zero for no timeout- Throws:
UnsupportedOperationException- If the DataSource implementation does not support the login timeout feature.SQLException- if a database access error occurs
-
setLogWriter
Sets the log writer being used by this data source.
Calls
createDataSource(), so has the side effect of initializing the connection pool.- Specified by:
setLogWriterin interfaceCommonDataSource- Specified by:
setLogWriterin interfaceDataSource- Parameters:
logWriter- The new log writer- Throws:
SQLException- if a database access error occurs
-
getRemoveAbandoned
public boolean getRemoveAbandoned()Flag to remove abandoned connections if they exceed the removeAbandonedTimout. Set to true or false, default false. If set to true a connection is considered abandoned and eligible for removal if it has been idle longer than the removeAbandonedTimeout. Setting this to true can recover db connections from poorly written applications which fail to close a connection.Abandonded connections are identified and removed when
getConnection()is invoked and the following conditions holdgetRemoveAbandoned()= truegetNumActive()>getMaxActive()- 3getNumIdle()invalid input: '<' 2
-
setRemoveAbandoned
public void setRemoveAbandoned(boolean removeAbandoned) - Parameters:
removeAbandoned- new removeAbandoned property value- See Also:
-
getRemoveAbandonedTimeout
public int getRemoveAbandonedTimeout()Timeout in seconds before an abandoned connection can be removed. Defaults to 300 seconds.- Returns:
- abandoned connection timeout
-
setRemoveAbandonedTimeout
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) - Parameters:
removeAbandonedTimeout- new removeAbandonedTimeout value
-
getLogAbandoned
public boolean getLogAbandoned()Flag to log stack traces for application code which abandoned a Statement or Connection.
Defaults to false.
Logging of abandoned Statements and Connections adds overhead for every Connection open or new Statement because a stack trace has to be generated.
-
setLogAbandoned
public void setLogAbandoned(boolean logAbandoned) - Parameters:
logAbandoned- new logAbandoned property value
-
addConnectionProperty
Add a custom connection property to the set that will be passed to our JDBC driver. This MUST be called before the first connection is retrieved (along with all the other configuration property setters). Calls to this method after the connection pool has been initialized have no effect.- Parameters:
name- Name of the custom connection propertyvalue- Value of the custom connection property
-
removeConnectionProperty
Remove a custom connection property.- Parameters:
name- Name of the custom connection property to remove- See Also:
-
setConnectionProperties
Sets the connection properties passed to driver.connect(...). Format of the string must be [propertyName=property;]* NOTE - The "user" and "password" properties will be added explicitly, so they do not need to be included here.- Parameters:
connectionProperties- the connection properties used to create new connections
-
close
Closes and releases all idle connections that are currently stored in the connection pool associated with this data source.
Connections that are checked out to clients when this method is invoked are not affected. When client applications subsequently invoke
Connection.close()to return these connections to the pool, the underlying JDBC connections are closed.Attempts to acquire connections using
getConnection()after this method has been invoked result in SQLExceptions.This method is idempotent - i.e., closing an already closed BasicDataSource has no effect and does not generate exceptions.
- Throws:
SQLException- if an error occurs closing idle connections
-
isClosed
public boolean isClosed()If true, this data source is closed and no more connections can be retrieved from this datasource.- Returns:
- true, if the data source is closed; false otherwise
-
isWrapperFor
- Specified by:
isWrapperForin interfaceWrapper- Throws:
SQLException
-
unwrap
- Specified by:
unwrapin interfaceWrapper- Throws:
SQLException
-
getParentLogger
- Specified by:
getParentLoggerin interfaceCommonDataSource- Throws:
SQLFeatureNotSupportedException
-