org.apache.commons.dbcp2

Class BasicDataSource

    • Method Detail

      • 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
      • 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
      • 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:
        Connection.getTransactionIsolation()
      • getDefaultQueryTimeout

        public Integer getDefaultQueryTimeout()
        Gets the default query timeout that will be used for Statements created from this connection. null means that the driver default will be used.
        Returns:
        The default query timeout in seconds.
      • setDefaultQueryTimeout

        public void setDefaultQueryTimeout(Integer defaultQueryTimeoutSeconds)
        Sets the default query timeout that will be used for Statements created from this connection. null means that the driver default will be used.
        Parameters:
        defaultQueryTimeoutSeconds - The default query timeout in seconds.
      • setDefaultCatalog

        public void setDefaultCatalog(String defaultCatalog)

        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
      • setCacheState

        public void setCacheState(boolean cacheState)
        Sets the state caching flag.
        Parameters:
        cacheState - The new value for the state caching flag
      • getDriver

        public Driver getDriver()
        Returns the JDBC Driver that has been configured for use by this pool.

        Note: This getter only returns the last value set by a call to setDriver(Driver). It does not return any driver instance that may have been created from the value set via setDriverClassName(String).

        Returns:
        the JDBC Driver that has been configured for use by this pool
      • setDriver

        public void setDriver(Driver driver)
        Sets the JDBC Driver instance to use for this 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:
        driver - The JDBC Driver instance to use for this pool.
      • setDriverClassName

        public void setDriverClassName(String driverClassName)

        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

        public ClassLoader getDriverClassLoader()
        Returns the class loader specified for loading the JDBC driver. Returns null if no class loader has been explicitly specified.

        Note: This getter only returns the last value set by a call to setDriverClassLoader(ClassLoader). It does not return the class loader of any driver that may have been set via setDriver(Driver).

        Returns:
        The class loader specified for loading the JDBC driver.
      • setDriverClassLoader

        public void setDriverClassLoader(ClassLoader driverClassLoader)

        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
      • getLifo

        public boolean getLifo()
        Returns the LIFO property.
        Specified by:
        getLifo in interface BasicDataSourceMXBean
        Returns:
        true if connection pool behaves as a LIFO queue.
      • setLifo

        public void setLifo(boolean lifo)
        Sets the LIFO property. True means the pool behaves as a LIFO queue; false means FIFO.
        Parameters:
        lifo - the new value for the LIFO property
      • getMaxTotal

        public int getMaxTotal()

        Returns the maximum number of active connections that can be allocated at the same time.

        A negative number means that there is no limit.

        Specified by:
        getMaxTotal in interface BasicDataSourceMXBean
        Returns:
        the maximum number of active connections
      • setMaxTotal

        public void setMaxTotal(int maxTotal)
        Sets the maximum total number of idle and borrows connections that can be active at the same time. Use a negative value for no limit.
        Parameters:
        maxTotal - the new value for maxTotal
        See Also:
        getMaxTotal()
      • getMaxIdle

        public int getMaxIdle()

        Returns the maximum number of connections that can remain idle in the pool. Excess idle connections are destroyed on return to the pool.

        A negative value indicates that there is no limit

        Specified by:
        getMaxIdle in interface BasicDataSourceMXBean
        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. Excess idle connections are destroyed on return to the pool.
        Parameters:
        maxIdle - the new value for maxIdle
        See Also:
        getMaxIdle()
      • setMinIdle

        public void setMinIdle(int minIdle)
        Sets the minimum number of idle connections in the pool. The pool attempts to ensure that minIdle connections are available when the idle object evictor runs. The value of this property has no effect unless timeBetweenEvictionRunsMillis has a positive value.
        Parameters:
        minIdle - the new value for minIdle
        See Also:
        GenericObjectPool.setMinIdle(int)
      • 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
      • getMaxWaitMillis

        public long getMaxWaitMillis()
        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.
        Specified by:
        getMaxWaitMillis in interface BasicDataSourceMXBean
        Returns:
        the maxWaitMillis property value
      • setMaxWaitMillis

        public void setMaxWaitMillis(long maxWaitMillis)
        Sets the MaxWaitMillis property. Use -1 to make the pool wait indefinitely.
        Parameters:
        maxWaitMillis - the new value for MaxWaitMillis
        See Also:
        getMaxWaitMillis()
      • 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
      • setMaxOpenPreparedStatements

        public void setMaxOpenPreparedStatements(int maxOpenStatements)

        Sets the value of the maxOpenPreparedStatements 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:
        maxOpenStatements - the new maximum number of prepared statements
      • setTestOnCreate

        public void setTestOnCreate(boolean testOnCreate)
        Sets the testOnCreate property. This property determines whether or not the pool will validate objects immediately after they are created by the pool
        Parameters:
        testOnCreate - new value for testOnCreate property
      • setTestOnBorrow

        public void setTestOnBorrow(boolean testOnBorrow)
        Sets the testOnBorrow property. This property determines whether or not the pool will validate objects before they are borrowed from the pool.
        Parameters:
        testOnBorrow - new value for testOnBorrow property
      • getTestOnReturn

        public boolean getTestOnReturn()
        Returns the value of the testOnReturn property.
        Returns:
        true if objects are validated before being returned to the pool
        See Also:
        testOnReturn
      • setTestOnReturn

        public void setTestOnReturn(boolean testOnReturn)
        Sets the testOnReturn property. This property determines whether or not the pool will validate objects before they are returned to the pool.
        Parameters:
        testOnReturn - new value for testOnReturn property
      • setSoftMinEvictableIdleTimeMillis

        public void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis)
        Sets the minimum amount of time a connection may sit idle in the pool before it is eligible for eviction by the idle object evictor, with the extra condition that at least "minIdle" connections remain in the pool.
        Parameters:
        softMinEvictableIdleTimeMillis - minimum amount of time a connection may sit idle in the pool before it is eligible for eviction, assuming there are minIdle idle connections in the pool.
        See Also:
        getSoftMinEvictableIdleTimeMillis()
      • getSoftMinEvictableIdleTimeMillis

        public long getSoftMinEvictableIdleTimeMillis()

        Returns the minimum amount of time a connection may sit idle in the pool before it is eligible for eviction by the idle object evictor, with the extra condition that at least "minIdle" connections remain in the pool.

        When minEvictableIdleTimeMillis is set to a positive value, minEvictableIdleTimeMillis is examined first by the idle connection evictor - i.e. when idle connections are visited by the evictor, idle time is first compared against minEvictableIdleTimeMillis (without considering the number of idle connections in the pool) and then against softMinEvictableIdleTimeMillis, including the minIdle, constraint.

        Specified by:
        getSoftMinEvictableIdleTimeMillis in interface BasicDataSourceMXBean
        Returns:
        minimum amount of time a connection may sit idle in the pool before it is eligible for eviction, assuming there are minIdle idle connections in the pool
      • getEvictionPolicyClassName

        public String getEvictionPolicyClassName()
        Gets the EvictionPolicy implementation in use with this connection pool.
        Returns:
        The EvictionPolicy implementation in use with this connection pool.
      • setEvictionPolicyClassName

        public void setEvictionPolicyClassName(String evictionPolicyClassName)
        Sets the EvictionPolicy implementation to use with this connection pool.
        Parameters:
        evictionPolicyClassName - The fully qualified class name of the EvictionPolicy implementation
      • setTestWhileIdle

        public void setTestWhileIdle(boolean testWhileIdle)
        Sets the testWhileIdle property. This property determines whether or not the idle object evictor will validate connections.
        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.
        Specified by:
        getNumActive in interface BasicDataSourceMXBean
        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.
        Specified by:
        getNumIdle in interface BasicDataSourceMXBean
        Returns:
        the current number of idle connections
      • setPassword

        public void setPassword(String password)

        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
      • setUrl

        public void setUrl(String url)

        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
      • setUsername

        public void setUsername(String userName)

        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 user name
      • setValidationQuery

        public void setValidationQuery(String validationQuery)

        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
      • setValidationQueryTimeout

        public void setValidationQueryTimeout(int validationQueryTimeoutSeconds)
        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:
        validationQueryTimeoutSeconds - new validation query timeout value in seconds
      • getConnectionInitSqls

        public List<StringgetConnectionInitSqls()
        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
      • setConnectionInitSqls

        public void setConnectionInitSqls(Collection<String> connectionInitSqls)
        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
      • 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.
      • setMaxConnLifetimeMillis

        public void setMaxConnLifetimeMillis(long maxConnLifetimeMillis)

        Sets the maximum permitted lifetime of a connection in milliseconds. A value of zero or less indicates an infinite lifetime.

        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:
        maxConnLifetimeMillis - The maximum permitted lifetime of a connection in milliseconds.
      • setLogExpiredConnections

        public void setLogExpiredConnections(boolean logExpiredConnections)
        When getMaxConnLifetimeMillis() is set to limit connection lifetime, this property determines whether or not log messages are generated when the pool closes connections due to maximum lifetime exceeded. Set this property to false to suppress log messages when connections expire.
        Parameters:
        logExpiredConnections - Whether or not log messages are generated when the pool closes connections due to maximum lifetime exceeded.
      • getJmxName

        public String getJmxName()
        Returns the JMX name that has been requested for this DataSource. If the requested name is not valid, an alternative may be chosen.
        Returns:
        The JMX name that has been requested for this DataSource.
      • setJmxName

        public void setJmxName(String jmxName)
        Sets the JMX name that has been requested for this DataSource. If the requested name is not valid, an alternative may be chosen. This DataSource will attempt to register itself using this name. If another component registers this DataSource with JMX and this name is valid this name will be used in preference to any specified by the other component.
        Parameters:
        jmxName - The JMX name that has been requested for this DataSource
      • getEnableAutoCommitOnReturn

        public boolean getEnableAutoCommitOnReturn()
        Returns the value of the flag that controls whether or not connections being returned to the pool will be checked and configured with Connection.setAutoCommit(true) if the auto commit setting is false when the connection is returned. It is true by default.
        Returns:
        Whether or not connections being returned to the pool will be checked and configured with auto-commit.
      • setEnableAutoCommitOnReturn

        public void setEnableAutoCommitOnReturn(boolean enableAutoCommitOnReturn)
        Sets the value of the flag that controls whether or not connections being returned to the pool will be checked and configured with Connection.setAutoCommit(true) if the auto commit setting is false when the connection is returned. It is true by default.
        Parameters:
        enableAutoCommitOnReturn - Whether or not connections being returned to the pool will be checked and configured with auto-commit.
      • getRollbackOnReturn

        public boolean getRollbackOnReturn()
        Gets the current value of the flag that controls whether a connection will be rolled back when it is returned to the pool if auto commit is not enabled and the connection is not read only.
        Returns:
        whether a connection will be rolled back when it is returned to the pool.
      • setRollbackOnReturn

        public void setRollbackOnReturn(boolean rollbackOnReturn)
        Sets the flag that controls if a connection will be rolled back when it is returned to the pool if auto commit is not enabled and the connection is not read only.
        Parameters:
        rollbackOnReturn - whether a connection will be rolled back when it is returned to the pool.
      • setDisconnectionSqlCodes

        public void setDisconnectionSqlCodes(Collection<String> disconnectionSqlCodes)
        Sets the SQL_STATE codes considered to signal fatal conditions.

        Overrides the defaults in Utils.DISCONNECTION_SQL_CODES (plus anything starting with Utils.DISCONNECTION_SQL_CODE_PREFIX). If this property is non-null and getFastFailValidation() is true, whenever connections created by this datasource generate exceptions with SQL_STATE codes in this list, they will be marked as "fatally disconnected" and subsequent validations will fail fast (no attempt at isValid or validation query).

        If getFastFailValidation() is false setting this property has no effect.

        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:
        disconnectionSqlCodes - SQL_STATE codes considered to signal fatal conditions
        Since:
        2.1
      • setFastFailValidation

        public void setFastFailValidation(boolean fastFailValidation)
        Parameters:
        fastFailValidation - true means connections created by this factory will fast fail validation
        Since:
        2.1
        See Also:
        getFastFailValidation()
      • setLoginTimeout

        public void setLoginTimeout(int loginTimeout)
                             throws SQLException
        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:
        setLoginTimeout in interface CommonDataSource
        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
      • setRemoveAbandonedOnBorrow

        public void setRemoveAbandonedOnBorrow(boolean removeAbandonedOnBorrow)
        Parameters:
        removeAbandonedOnBorrow - true means abandoned connections may be removed when connections are borrowed from the pool.
        See Also:
        getRemoveAbandonedOnBorrow()
      • 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.

        Specified by:
        getLogAbandoned in interface BasicDataSourceMXBean
        Returns:
        getLogAbandoned()
      • setLogAbandoned

        public void setLogAbandoned(boolean logAbandoned)
        Parameters:
        logAbandoned - new logAbandoned property value
      • getAbandonedLogWriter

        public PrintWriter getAbandonedLogWriter()
        Gets the print writer used by this configuration to log information on abandoned objects.
        Returns:
        The print writer used by this configuration to log information on abandoned objects.
      • setAbandonedLogWriter

        public void setAbandonedLogWriter(PrintWriter logWriter)
        Sets the print writer to be used by this configuration to log information on abandoned objects.
        Parameters:
        logWriter - The new log writer
      • getAbandonedUsageTracking

        public boolean getAbandonedUsageTracking()
        If the connection pool implements UsageTracking, should the connection pool record a stack trace every time a method is called on a pooled connection and retain the most recent stack trace to aid debugging of abandoned connections?
        Specified by:
        getAbandonedUsageTracking in interface BasicDataSourceMXBean
        Returns:
        true if usage tracking is enabled
      • setAbandonedUsageTracking

        public void setAbandonedUsageTracking(boolean usageTracking)
        If the connection pool implements UsageTracking, configure whether the connection pool should record a stack trace every time a method is called on a pooled connection and retain the most recent stack trace to aid debugging of abandoned connections.
        Parameters:
        usageTracking - A value of true will enable the recording of a stack trace on every use of a pooled connection
      • addConnectionProperty

        public void addConnectionProperty(String name,
                                          String value)
        Adds 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 property
        value - Value of the custom connection property
      • setConnectionProperties

        public void setConnectionProperties(String connectionProperties)
        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

        public void close()
                   throws SQLException

        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.

        Specified by:
        close in interface AutoCloseable
        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.
        Specified by:
        isClosed in interface BasicDataSourceMXBean
        Returns:
        true, if the data source is closed; false otherwise
      • invalidateConnection

        public void invalidateConnection(Connection connection)
                                  throws IllegalStateException
        Manually invalidates a connection, effectively requesting the pool to try to close it, remove it from the pool and reclaim pool capacity.
        Parameters:
        connection - The Connection to invalidate.
        Throws:
        IllegalStateException - if invalidating the connection failed.
        Since:
        2.1
      • createConnectionPool

        protected void createConnectionPool(PoolableConnectionFactory factory)
        Creates a connection pool for this datasource. This method only exists so subclasses can replace the implementation class.

        This implementation configures all pool properties other than timeBetweenEvictionRunsMillis. Setting that property is deferred to startPoolMaintenance(), since setting timeBetweenEvictionRunsMillis to a positive value causes GenericObjectPool's eviction timer to be started.

      • startPoolMaintenance

        protected void startPoolMaintenance()
        Starts the connection pool maintenance task, if configured.

Copyright © 2001–2018 The Apache Software Foundation. All rights reserved.