- All Implemented Interfaces:
DatabaseAccess
,AutoCloseable
DatabaseConnection
represents the scope of an overall transaction.
It is used to only get actual database connections when needed.- Author:
- AO Industries, Inc.
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from interface com.aoapps.dbc.DatabaseAccess
DatabaseAccess.Null
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int
The fetch size given toStatement.setFetchSize(int)
. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
close()
Closes and/or releases the current connection back to the pool.Closes and/or releases the current connection back to the pool.void
commit()
Commits the current transaction.doubleStream
(int isolationLevel, boolean readOnly, String sql, Object... params) Query the database with aDoubleStream
return type.Gets the read/write connection to the database with a transaction level ofConnections.DEFAULT_TRANSACTION_ISOLATION
, warning when a connection is already used by this thread.getConnection
(boolean readOnly) Gets the connection to the database with a transaction level ofConnections.DEFAULT_TRANSACTION_ISOLATION
, warning when a connection is already used by this thread.getConnection
(int maxConnections) Gets the read/write connection to the database with a transaction level ofConnections.DEFAULT_TRANSACTION_ISOLATION
.getConnection
(int isolationLevel, boolean readOnly) Gets the connection to the database, warning when a connection is already used by this thread.getConnection
(int isolationLevel, boolean readOnly, int maxConnections) Gets the connection to the database.Query the database with anIntStream
return type.boolean
isClosed()
boolean
Deprecated.long
largeUpdate
(String sql, Object... params) Performs an update on the database and returns the number of rows affected.longStream
(int isolationLevel, boolean readOnly, String sql, Object... params) Query the database with aLongStream
return type.Adds an on-commit event handler, which are called in order just after the transaction has been successfully committed.onRollback
(RunnableE<?> onRollback) Adds an on-rollback event handler, which are called in reverse order just before the transaction will be rolled-back.<T,
Ex extends Throwable>
TqueryCall
(int isolationLevel, boolean readOnly, Class<? extends Ex> exClass, ResultSetCallableE<? extends T, ? extends Ex> resultSetCallable, String sql, Object... params) Query the database, calling theResultSetCallableE
once.void
Deprecated, for removal: This API element is subject to removal in a future version.Please useclose()
boolean
rollback()
Rolls back the current connection, if have connection and is not auto-commit.Rolls back the current connection, if have connection and is not auto-commit.boolean
Deprecated, for removal: This API element is subject to removal in a future version.Please userollback()
.Deprecated, for removal: This API element is subject to removal in a future version.Please userollback(java.lang.Throwable)
.protected static void
setParam
(Connection conn, PreparedStatement pstmt, int pos, Object param) static void
setParams
(Connection conn, PreparedStatement pstmt, Object... params) stream
(int isolationLevel, boolean readOnly, Class<? extends Ex> exClass, ObjectFactoryE<? extends T, ? extends Ex> objectFactory, String sql, Object... params) Query the database with aStream<T>
return type, objects are created with the provided factory.<V> V
transactionCall
(DatabaseCallable<? extends V> callable) Deprecated.DatabaseConnection
is already within a transaction.<V> V
transactionCall
(CallableE<? extends V, ? extends SQLException> callable) Deprecated.DatabaseConnection
is already within a transaction.<V,
Ex extends Throwable>
VtransactionCall
(Class<? extends Ex> exClass, DatabaseCallableE<? extends V, ? extends Ex> callable) Deprecated.DatabaseConnection
is already within a transaction.<V,
Ex extends Throwable>
VtransactionCall
(Class<? extends Ex> exClass, CallableE<? extends V, ? extends Ex> callable) Deprecated.DatabaseConnection
is already within a transaction.void
transactionRun
(DatabaseRunnable runnable) Deprecated.DatabaseConnection
is already within a transaction.void
transactionRun
(RunnableE<? extends SQLException> runnable) Deprecated.DatabaseConnection
is already within a transaction.<Ex extends Throwable>
voidtransactionRun
(Class<? extends Ex> exClass, DatabaseRunnableE<? extends Ex> runnable) Deprecated.DatabaseConnection
is already within a transaction.<Ex extends Throwable>
voidtransactionRun
(Class<? extends Ex> exClass, RunnableE<? extends Ex> runnable) Deprecated.DatabaseConnection
is already within a transaction.int
Performs an update on the database and returns the number of rows affected.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface com.aoapps.dbc.DatabaseAccess
doubleStream, doubleStreamUpdate, executeBigDecimalQuery, executeBigDecimalQuery, executeBigDecimalUpdate, executeBooleanQuery, executeBooleanQuery, executeBooleanUpdate, executeByteArrayQuery, executeByteArrayQuery, executeByteArrayUpdate, executeDateQuery, executeDateQuery, executeDateUpdate, executeIntListQuery, executeIntListQuery, executeIntListUpdate, executeIntQuery, executeIntQuery, executeIntUpdate, executeLongListQuery, executeLongListQuery, executeLongListUpdate, executeLongQuery, executeLongQuery, executeLongUpdate, executeObjectCollectionQuery, executeObjectCollectionQuery, executeObjectCollectionQuery, executeObjectCollectionQuery, executeObjectCollectionQuery, executeObjectCollectionQuery, executeObjectCollectionUpdate, executeObjectCollectionUpdate, executeObjectCollectionUpdate, executeObjectListQuery, executeObjectListQuery, executeObjectListQuery, executeObjectListQuery, executeObjectListQuery, executeObjectListQuery, executeObjectListUpdate, executeObjectListUpdate, executeObjectListUpdate, executeObjectQuery, executeObjectQuery, executeObjectQuery, executeObjectQuery, executeObjectQuery, executeObjectQuery, executeObjectUpdate, executeObjectUpdate, executeObjectUpdate, executeQuery, executeQuery, executeQuery, executeQuery, executeShortListQuery, executeShortListQuery, executeShortListUpdate, executeShortQuery, executeShortQuery, executeShortUpdate, executeStringListQuery, executeStringListQuery, executeStringListUpdate, executeStringQuery, executeStringQuery, executeStringUpdate, executeTimestampQuery, executeTimestampQuery, executeTimestampUpdate, executeUpdate, executeUpdate, executeUpdate, intStream, intStreamUpdate, longStream, longStreamUpdate, queryBigDecimal, queryBigDecimal, queryBigDecimal, queryBigDecimalNullable, queryBigDecimalOptional, queryBigDecimalOptionalNullable, queryBoolean, queryBoolean, queryBoolean, queryBooleanNullable, queryBooleanOptional, queryBooleanOptionalNullable, queryByteArray, queryByteArray, queryByteArray, queryByteArrayNullable, queryByteArrayOptional, queryByteArrayOptionalNullable, queryCall, queryCall, queryCall, queryCollection, queryCollection, queryCollection, queryCollection, queryDate, queryDate, queryDate, queryDateNullable, queryDateOptional, queryDateOptionalNullable, queryDouble, queryDouble, queryDouble, queryDoubleNullable, queryDoubleOptional, queryDoubleOptionalNullable, queryFloat, queryFloat, queryFloat, queryFloatNullable, queryFloatOptional, queryFloatOptionalNullable, queryInt, queryInt, queryInt, queryIntList, queryIntList, queryIntNullable, queryIntOptional, queryIntOptionalNullable, queryList, queryList, queryList, queryList, queryLong, queryLong, queryLong, queryLongList, queryLongList, queryLongNullable, queryLongOptional, queryLongOptionalNullable, queryNewCollection, queryNewCollection, queryNewCollection, queryNewCollection, queryObject, queryObject, queryObject, queryObject, queryObject, queryObject, queryObjectNullable, queryObjectNullable, queryObjectOptional, queryObjectOptional, queryObjectOptionalNullable, queryObjectOptionalNullable, queryRun, queryRun, queryRun, queryRun, queryShort, queryShort, queryShort, queryShortNullable, queryShortOptional, queryShortOptionalNullable, queryString, queryString, queryString, queryStringList, queryStringList, queryStringNullable, queryStringOptional, queryStringOptionalNullable, queryTimestamp, queryTimestamp, queryTimestamp, queryTimestampNullable, queryTimestampOptional, queryTimestampOptionalNullable, stream, stream, stream, streamOptional, streamOptional, streamOptional, streamOptional, streamOptionalUpdate, streamOptionalUpdate, streamString, streamString, streamStringUpdate, streamUpdate, streamUpdate, updateBigDecimal, updateBigDecimalNullable, updateBigDecimalOptional, updateBigDecimalOptionalNullable, updateBoolean, updateBooleanNullable, updateBooleanOptional, updateBooleanOptionalNullable, updateByteArray, updateByteArrayNullable, updateByteArrayOptional, updateByteArrayOptionalNullable, updateCall, updateCall, updateCollection, updateCollection, updateDate, updateDateNullable, updateDateOptional, updateDateOptionalNullable, updateDouble, updateDoubleNullable, updateDoubleOptional, updateDoubleOptionalNullable, updateFloat, updateFloatNullable, updateFloatOptional, updateFloatOptionalNullable, updateInt, updateIntList, updateIntNullable, updateIntOptional, updateIntOptionalNullable, updateList, updateList, updateLong, updateLongList, updateLongNullable, updateLongOptional, updateLongOptionalNullable, updateNewCollection, updateNewCollection, updateObject, updateObject, updateObjectNullable, updateObjectNullable, updateObjectOptional, updateObjectOptional, updateObjectOptionalNullable, updateObjectOptionalNullable, updateRun, updateRun, updateShort, updateShortNullable, updateShortOptional, updateShortOptionalNullable, updateString, updateStringList, updateStringNullable, updateStringOptional, updateStringOptionalNullable, updateTimestamp, updateTimestampNullable, updateTimestampOptional, updateTimestampOptionalNullable
-
Field Details
-
FETCH_SIZE
public static final int FETCH_SIZEThe fetch size given toStatement.setFetchSize(int)
. This value may be increased over time as the amount of typical system memory increases. As this may affect the number of round trips, and the speed of light is not likely to change, future increases may be of benefit.We've been using a value of
1000
for nearly two decades. As of the year 2020, we've bumped this up to10000
.- See Also:
-
-
Constructor Details
-
DatabaseConnection
-
-
Method Details
-
getDatabase
-
isInTransaction
Deprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Checks if the current thread is in a transaction.- Specified by:
isInTransaction
in interfaceDatabaseAccess
- Returns:
true
sinceDatabaseConnection
is already within a transaction.- See Also:
-
transactionCall
@Deprecated public <V> V transactionCall(CallableE<? extends V, ? extends SQLException> callable) throws SQLExceptionDeprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionCall
in interfaceDatabaseAccess
- Throws:
SQLException
- See Also:
- Rolls-back the transaction on
-
transactionCall
@Deprecated public <V,Ex extends Throwable> V transactionCall(Class<? extends Ex> exClass, CallableE<? extends V, ? extends Ex> callable) throws SQLException, ExDeprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionCall
in interfaceDatabaseAccess
- Type Parameters:
Ex
- An arbitrary exception type that may be thrown- Throws:
SQLException
Ex
- See Also:
- Rolls-back the transaction on
-
transactionCall
@Deprecated public <V> V transactionCall(DatabaseCallable<? extends V> callable) throws SQLException Deprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionCall
in interfaceDatabaseAccess
- Throws:
SQLException
- See Also:
- Rolls-back the transaction on
-
transactionCall
@Deprecated public <V,Ex extends Throwable> V transactionCall(Class<? extends Ex> exClass, DatabaseCallableE<? extends V, ? extends Ex> callable) throws SQLException, ExDeprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionCall
in interfaceDatabaseAccess
- Type Parameters:
Ex
- An arbitrary exception type that may be thrown- Throws:
SQLException
Ex
- See Also:
- Rolls-back the transaction on
-
transactionRun
@Deprecated public void transactionRun(RunnableE<? extends SQLException> runnable) throws SQLException Deprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionRun
in interfaceDatabaseAccess
- Throws:
SQLException
- See Also:
- Rolls-back the transaction on
-
transactionRun
@Deprecated public <Ex extends Throwable> void transactionRun(Class<? extends Ex> exClass, RunnableE<? extends Ex> runnable) throws SQLException, Ex Deprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionRun
in interfaceDatabaseAccess
- Type Parameters:
Ex
- An arbitrary exception type that may be thrown- Throws:
SQLException
Ex
- See Also:
- Rolls-back the transaction on
-
transactionRun
Deprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionRun
in interfaceDatabaseAccess
- Throws:
SQLException
- See Also:
- Rolls-back the transaction on
-
transactionRun
@Deprecated public <Ex extends Throwable> void transactionRun(Class<? extends Ex> exClass, DatabaseRunnableE<? extends Ex> runnable) throws SQLException, Ex Deprecated.DatabaseConnection
is already within a transaction.Description copied from interface:DatabaseAccess
Executes an arbitrary transaction, providing automatic commit, rollback, and connection management.- Rolls-back the transaction on
NoRowException
,NullDataException
, orExtraRowException
on the outer-most transaction only. - Rolls-back the transaction on all other
Throwable
.
The connection allocated is stored as a
ThreadLocal
and will be automatically reused if another transaction is performed within this transaction. Any nested transaction will automatically become part of the enclosing transaction. For safety, a nested transaction will still rollback the entire transaction on any exception.- Specified by:
transactionRun
in interfaceDatabaseAccess
- Type Parameters:
Ex
- An arbitrary exception type that may be thrown- Throws:
SQLException
Ex
- See Also:
- Rolls-back the transaction on
-
getConnection
Gets the read/write connection to the database with a transaction level ofConnections.DEFAULT_TRANSACTION_ISOLATION
, warning when a connection is already used by this thread.Uses a deferred connection strategy. If not previously connected, allocates the connection now. This allows applications to create
DatabaseConnection
at no cost, only connecting to the database when first needed. This is helpful for when a transaction scope is established at a high level, where the actual use (or lack thereof) of the database is unknown.The default auto-commit state depends on the read-only, isolation levels, and the presence of any on-commit or on-rollback event listeners. Upon initial connection, auto-commit is enabled. It then remains unchanged while is read-only, at an isolation level of
Connection.TRANSACTION_READ_COMMITTED
or below, and has no event listeners. This means, conversely, that auto-commit is disabled when is read-write, at an isolation level ofConnection.TRANSACTION_REPEATABLE_READ
or above, or has any event listeners.When a connection already exists, its read-only mode may be changed, but may not be changed on a connection that has auto-commit disabled (which typically means it was already read-write, at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, or had event listeners).With the default auto-commit behavior (auto-commit not disabled by application), it is an error to try to change from read-only to read-write while at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, as the necessary actions to make the change would break the repeatable-read guarantee.Read-write connections will not be set back to read-only mode when the connection has auto-commit disabled, thus the read-only flag is an optimization and an extra level of protection, but cannot be relied upon due to potentially being within the scope of a larger read-write transaction.
When a connection already exists, its isolation level may be increased, but will never be decreased. However, the ability to change the isolation level within a transaction is driver dependent. It is best to set the highest isolation level that will be required at the beginning of the transaction.
If all the connections in the pool are busy and the pool is at capacity, waits until a connection becomes available.
The connection will be a
FailFastConnection
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The fail-fast connection is used to determine whether to roll-back or commit during automatic transaction management.The connection will also be a
ConnectionTracker
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The connection tracking is used to close/free all objects before returning the connection to the underlying pool.- Returns:
- The read/write connection to the database.
This connection may be used in try-with-resources, but any calls to
Connection.close()
are ignored. Instead, the connection is released and/or closed when thisDatabaseConnection
is closed.Connection.commit()
andConnection.rollback()
should not be used directly, since they will not fire anyonCommit(com.aoapps.lang.RunnableE)
oronRollback(com.aoapps.lang.RunnableE)
events. Instead, please usecommit()
androllback()
. - Throws:
SQLException
- when an error occurs, or when a thread attempts to allocate more than half the pool- See Also:
-
getConnection
Gets the read/write connection to the database with a transaction level ofConnections.DEFAULT_TRANSACTION_ISOLATION
.Uses a deferred connection strategy. If not previously connected, allocates the connection now. This allows applications to create
DatabaseConnection
at no cost, only connecting to the database when first needed. This is helpful for when a transaction scope is established at a high level, where the actual use (or lack thereof) of the database is unknown.The default auto-commit state depends on the read-only, isolation levels, and the presence of any on-commit or on-rollback event listeners. Upon initial connection, auto-commit is enabled. It then remains unchanged while is read-only, at an isolation level of
Connection.TRANSACTION_READ_COMMITTED
or below, and has no event listeners. This means, conversely, that auto-commit is disabled when is read-write, at an isolation level ofConnection.TRANSACTION_REPEATABLE_READ
or above, or has any event listeners.When a connection already exists, its read-only mode may be changed, but may not be changed on a connection that has auto-commit disabled (which typically means it was already read-write, at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, or had event listeners).With the default auto-commit behavior (auto-commit not disabled by application), it is an error to try to change from read-only to read-write while at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, as the necessary actions to make the change would break the repeatable-read guarantee.Read-write connections will not be set back to read-only mode when the connection has auto-commit disabled, thus the read-only flag is an optimization and an extra level of protection, but cannot be relied upon due to potentially being within the scope of a larger read-write transaction.
When a connection already exists, its isolation level may be increased, but will never be decreased. However, the ability to change the isolation level within a transaction is driver dependent. It is best to set the highest isolation level that will be required at the beginning of the transaction.
If all the connections in the pool are busy and the pool is at capacity, waits until a connection becomes available.
The connection will be a
FailFastConnection
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The fail-fast connection is used to determine whether to roll-back or commit during automatic transaction management.The connection will also be a
ConnectionTracker
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The connection tracking is used to close/free all objects before returning the connection to the underlying pool.- Parameters:
maxConnections
- The maximum number of connections expected to be used by the current thread. This should normally be one to avoid potential deadlock.The connection will continue to be considered used by the allocating thread until released (via
Connection.close()
, even if the connection is shared by another thread.- Returns:
- The read/write connection to the database.
This connection may be used in try-with-resources, but any calls to
Connection.close()
are ignored. Instead, the connection is released and/or closed when thisDatabaseConnection
is closed.Connection.commit()
andConnection.rollback()
should not be used directly, since they will not fire anyonCommit(com.aoapps.lang.RunnableE)
oronRollback(com.aoapps.lang.RunnableE)
events. Instead, please usecommit()
androllback()
. - Throws:
SQLException
- when an error occurs, or when a thread attempts to allocate more than half the pool- See Also:
-
getConnection
Gets the connection to the database with a transaction level ofConnections.DEFAULT_TRANSACTION_ISOLATION
, warning when a connection is already used by this thread.Uses a deferred connection strategy. If not previously connected, allocates the connection now. This allows applications to create
DatabaseConnection
at no cost, only connecting to the database when first needed. This is helpful for when a transaction scope is established at a high level, where the actual use (or lack thereof) of the database is unknown.The default auto-commit state depends on the read-only, isolation levels, and the presence of any on-commit or on-rollback event listeners. Upon initial connection, auto-commit is enabled. It then remains unchanged while is read-only, at an isolation level of
Connection.TRANSACTION_READ_COMMITTED
or below, and has no event listeners. This means, conversely, that auto-commit is disabled when is read-write, at an isolation level ofConnection.TRANSACTION_REPEATABLE_READ
or above, or has any event listeners.When a connection already exists, its read-only mode may be changed, but may not be changed on a connection that has auto-commit disabled (which typically means it was already read-write, at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, or had event listeners).With the default auto-commit behavior (auto-commit not disabled by application), it is an error to try to change from read-only to read-write while at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, as the necessary actions to make the change would break the repeatable-read guarantee.Read-write connections will not be set back to read-only mode when the connection has auto-commit disabled, thus the read-only flag is an optimization and an extra level of protection, but cannot be relied upon due to potentially being within the scope of a larger read-write transaction.
When a connection already exists, its isolation level may be increased, but will never be decreased. However, the ability to change the isolation level within a transaction is driver dependent. It is best to set the highest isolation level that will be required at the beginning of the transaction.
If all the connections in the pool are busy and the pool is at capacity, waits until a connection becomes available.
The connection will be a
FailFastConnection
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The fail-fast connection is used to determine whether to roll-back or commit during automatic transaction management.The connection will also be a
ConnectionTracker
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The connection tracking is used to close/free all objects before returning the connection to the underlying pool.- Parameters:
readOnly
- Theread-only flag
. Please note: a read-write connection will always be returned while already in the scope of an overall read-write transaction.- Returns:
- The connection to the database.
This connection may be used in try-with-resources, but any calls to
Connection.close()
are ignored. Instead, the connection is released and/or closed when thisDatabaseConnection
is closed.Connection.commit()
andConnection.rollback()
should not be used directly, since they will not fire anyonCommit(com.aoapps.lang.RunnableE)
oronRollback(com.aoapps.lang.RunnableE)
events. Instead, please usecommit()
androllback()
. - Throws:
SQLException
- when an error occurs, or when a thread attempts to allocate more than half the pool- See Also:
-
getConnection
Gets the connection to the database, warning when a connection is already used by this thread.Uses a deferred connection strategy. If not previously connected, allocates the connection now. This allows applications to create
DatabaseConnection
at no cost, only connecting to the database when first needed. This is helpful for when a transaction scope is established at a high level, where the actual use (or lack thereof) of the database is unknown.The default auto-commit state depends on the read-only, isolation levels, and the presence of any on-commit or on-rollback event listeners. Upon initial connection, auto-commit is enabled. It then remains unchanged while is read-only, at an isolation level of
Connection.TRANSACTION_READ_COMMITTED
or below, and has no event listeners. This means, conversely, that auto-commit is disabled when is read-write, at an isolation level ofConnection.TRANSACTION_REPEATABLE_READ
or above, or has any event listeners.When a connection already exists, its read-only mode may be changed, but may not be changed on a connection that has auto-commit disabled (which typically means it was already read-write, at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, or had event listeners).With the default auto-commit behavior (auto-commit not disabled by application), it is an error to try to change from read-only to read-write while at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, as the necessary actions to make the change would break the repeatable-read guarantee.Read-write connections will not be set back to read-only mode when the connection has auto-commit disabled, thus the read-only flag is an optimization and an extra level of protection, but cannot be relied upon due to potentially being within the scope of a larger read-write transaction.
When a connection already exists, its isolation level may be increased, but will never be decreased. However, the ability to change the isolation level within a transaction is driver dependent. It is best to set the highest isolation level that will be required at the beginning of the transaction.
If all the connections in the pool are busy and the pool is at capacity, waits until a connection becomes available.
The connection will be a
FailFastConnection
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The fail-fast connection is used to determine whether to roll-back or commit during automatic transaction management.The connection will also be a
ConnectionTracker
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The connection tracking is used to close/free all objects before returning the connection to the underlying pool.- Parameters:
isolationLevel
- Thetransaction isolation level
. Please note: a connection of a higher transaction isolation level may be returned while already in the scope of an overall transaction.readOnly
- Theread-only flag
. Please note: a read-write connection will always be returned while already in the scope of an overall read-write transaction.- Returns:
- The connection to the database.
This connection may be used in try-with-resources, but any calls to
Connection.close()
are ignored. Instead, the connection is released and/or closed when thisDatabaseConnection
is closed.Connection.commit()
andConnection.rollback()
should not be used directly, since they will not fire anyonCommit(com.aoapps.lang.RunnableE)
oronRollback(com.aoapps.lang.RunnableE)
events. Instead, please usecommit()
androllback()
. - Throws:
SQLException
- when an error occurs, or when a thread attempts to allocate more than half the pool- See Also:
-
getConnection
public Connection getConnection(int isolationLevel, boolean readOnly, int maxConnections) throws SQLException Gets the connection to the database.Uses a deferred connection strategy. If not previously connected, allocates the connection now. This allows applications to create
DatabaseConnection
at no cost, only connecting to the database when first needed. This is helpful for when a transaction scope is established at a high level, where the actual use (or lack thereof) of the database is unknown.The default auto-commit state depends on the read-only, isolation levels, and the presence of any on-commit or on-rollback event listeners. Upon initial connection, auto-commit is enabled. It then remains unchanged while is read-only, at an isolation level of
Connection.TRANSACTION_READ_COMMITTED
or below, and has no event listeners. This means, conversely, that auto-commit is disabled when is read-write, at an isolation level ofConnection.TRANSACTION_REPEATABLE_READ
or above, or has any event listeners.When a connection already exists, its read-only mode may be changed, but may not be changed on a connection that has auto-commit disabled (which typically means it was already read-write, at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, or had event listeners).With the default auto-commit behavior (auto-commit not disabled by application), it is an error to try to change from read-only to read-write while at an isolation level of
Connection.TRANSACTION_REPEATABLE_READ
or above, as the necessary actions to make the change would break the repeatable-read guarantee.Read-write connections will not be set back to read-only mode when the connection has auto-commit disabled, thus the read-only flag is an optimization and an extra level of protection, but cannot be relied upon due to potentially being within the scope of a larger read-write transaction.
When a connection already exists, its isolation level may be increased, but will never be decreased. However, the ability to change the isolation level within a transaction is driver dependent. It is best to set the highest isolation level that will be required at the beginning of the transaction.
If all the connections in the pool are busy and the pool is at capacity, waits until a connection becomes available.
The connection will be a
FailFastConnection
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The fail-fast connection is used to determine whether to roll-back or commit during automatic transaction management.The connection will also be a
ConnectionTracker
, which may be unwrapped viaWrapper.unwrap(java.lang.Class)
. The connection tracking is used to close/free all objects before returning the connection to the underlying pool.- Parameters:
isolationLevel
- Thetransaction isolation level
. Please note: a connection of a higher transaction isolation level may be returned while already in the scope of an overall transaction.readOnly
- Theread-only flag
. Please note: a read-write connection will always be returned while already in the scope of an overall read-write transaction.maxConnections
- The maximum number of connections expected to be used by the current thread. This should normally be one to avoid potential deadlock.The connection will continue to be considered used by the allocating thread until released (via
Connection.close()
, even if the connection is shared by another thread.- Returns:
- The connection to the database.
This connection may be used in try-with-resources, but any calls to
Connection.close()
are ignored. Instead, the connection is released and/or closed when thisDatabaseConnection
is closed.Connection.commit()
andConnection.rollback()
should not be used directly, since they will not fire anyonCommit(com.aoapps.lang.RunnableE)
oronRollback(com.aoapps.lang.RunnableE)
events. Instead, please usecommit()
androllback()
. - Throws:
SQLException
- when an error occurs, or when a thread attempts to allocate more than half the pool- See Also:
-
setParam
protected static void setParam(Connection conn, PreparedStatement pstmt, int pos, Object param) throws SQLException - Throws:
SQLException
-
setParams
public static void setParams(Connection conn, PreparedStatement pstmt, Object... params) throws SQLException - Throws:
SQLException
-
onCommit
Adds an on-commit event handler, which are called in order just after the transaction has been successfully committed.Exceptions of any on-commit event handler will be propagated. When handler throws
Error
,RuntimeException
, orSQLException
, the exception is propagated directly. Any otherThrowable
is wrapped inEventException
.When an on-commit event handler throws any exception, remaining on-commit event handlers registered after the failed one will not be fired.
When adding the first non-null event handler (either of
onCommit(com.aoapps.lang.RunnableE)
oronRollback(com.aoapps.lang.RunnableE)
), if the connection exists and currently has auto-commit enabled, auto-commit will be disabled. This is so the event scope can match the transaction scope of the underlying database.- Parameters:
onCommit
- The event handler, may benull
which will simply be ignored.- Throws:
SQLException
- See Also:
-
onRollback
Adds an on-rollback event handler, which are called in reverse order just before the transaction will be rolled-back.Exceptions of any on-rollback event handler will be propagated. When handler throws
Error
,RuntimeException
, orSQLException
, the exception is propagated directly. Any otherThrowable
is wrapped inEventException
.When an on-rollback event handler throws any exception, remaining on-rollback event handlers registered before the failed one will not be fired.
When adding the first non-null event handler (either of
onCommit(com.aoapps.lang.RunnableE)
oronRollback(com.aoapps.lang.RunnableE)
), if the connection exists and currently has auto-commit enabled, auto-commit will be disabled. This is so the event scope can match the transaction scope of the underlying database.- Parameters:
onRollback
- The event handler, may benull
which will simply be ignored.- Throws:
SQLException
- See Also:
-
commit
Commits the current transaction.Once the underlying transaction (if any) is successfully committed, any on-rollback event handlers are discarded, then all on-commit event handlers are fired in order. When an on-commit event handler throws any exception, remaining on-commit event handlers registered after the failed one will not be fired.
- Throws:
SQLException
-
isClosed
- Throws:
SQLException
-
releaseConnection
Deprecated, for removal: This API element is subject to removal in a future version.Please useclose()
- Throws:
SQLException
-
close
Closes and/or releases the current connection back to the pool.Any on-commit event handlers are discarded.
All on-rollback event handlers are fired in reverse order. When an on-rollback event handler throws any exception, remaining on-rollback event handlers registered before the failed one will not be fired.
Any transaction in-progress is rolled-back. This will still be done even when an on-rollback event handler has thrown an exception.
- Specified by:
close
in interfaceAutoCloseable
- Throws:
SQLException
- See Also:
-
close
Closes and/or releases the current connection back to the pool.Any on-commit event handlers are discarded.
All on-rollback event handlers are fired in reverse order. When an on-rollback event handler throws any exception, remaining on-rollback event handlers registered before the failed one will not be fired.
Any transaction in-progress is rolled-back. This will still be done even when an on-rollback event handler has thrown an exception.
- Parameters:
t0
- Any exceptions will be added here viaThrowables.addSuppressed(java.lang.Throwable, java.lang.Throwable)
- Returns:
- The given exception, or new exception, or
null
when none given and none new - See Also:
-
rollback
Rolls back the current connection, if have connection and is not auto-commit.Any on-commit event handlers are discarded.
All on-rollback event handlers are fired in reverse order. When an on-rollback event handler throws any exception, remaining on-rollback event handlers registered before the failed one will not be fired.
Any transaction in-progress is rolled-back. This will still be done even when an on-rollback event handler has thrown an exception.
- Returns:
true
when connected and rolled-back (or is auto-commit)- Throws:
SQLException
-
rollback
Rolls back the current connection, if have connection and is not auto-commit.Any on-commit event handlers are discarded.
All on-rollback event handlers are fired in reverse order. When an on-rollback event handler throws any exception, remaining on-rollback event handlers registered before the failed one will not be fired.
Any transaction in-progress is rolled-back. This will still be done even when an on-rollback event handler has thrown an exception.
- Parameters:
t0
- Any exceptions will be added here viaThrowables.addSuppressed(java.lang.Throwable, java.lang.Throwable)
- Returns:
- The given exception, or new exception, or
null
when none given and none new - See Also:
-
rollbackAndClose
Deprecated, for removal: This API element is subject to removal in a future version.Please userollback()
. The connection will be validated duringclose()
when there is any unresolved fail-fast state.Rolls back the current connection, if have connection and is not auto-commit, and forces the underlying connection closed viaConnection.abort(java.util.concurrent.Executor)
. This close is distinct fromclose()
, which is intended for releasing to the underlying pool viaConnection.close()
.Any on-commit event handlers are discarded.
All on-rollback event handlers are fired in reverse order. When an on-rollback event handler throws any exception, remaining on-rollback event handlers registered before the failed one will not be fired.
Any transaction in-progress is rolled-back. This will still be done even when an on-rollback event handler has thrown an exception.
- Returns:
true
when connected and rolled-back (or is auto-commit)- Throws:
SQLException
- See Also:
-
rollbackAndClose
Deprecated, for removal: This API element is subject to removal in a future version.Please userollback(java.lang.Throwable)
. The connection will be validated duringclose(java.lang.Throwable)
when there is any unresolved fail-fast state.Rolls back the current connection, if have connection and is not auto-commit, and forces the underlying connection closed viaConnection.abort(java.util.concurrent.Executor)
. This close is distinct fromclose()
, which is intended for releasing to the underlying pool viaConnection.close()
.Any on-commit event handlers are discarded.
All on-rollback event handlers are fired in reverse order. When an on-rollback event handler throws any exception, remaining on-rollback event handlers registered before the failed one will not be fired.
Any transaction in-progress is rolled-back. This will still be done even when an on-rollback event handler has thrown an exception.
- Parameters:
t0
- Any exceptions will be added here viaThrowables.addSuppressed(java.lang.Throwable, java.lang.Throwable)
- Returns:
- The given exception, or new exception, or
null
when none given and none new - See Also:
-
doubleStream
public DoubleStream doubleStream(int isolationLevel, boolean readOnly, String sql, Object... params) throws NullDataException, SQLException Description copied from interface:DatabaseAccess
Query the database with aDoubleStream
return type.- Specified by:
doubleStream
in interfaceDatabaseAccess
- Throws:
NullDataException
- When has a SQL NULL value.SQLException
-
intStream
public IntStream intStream(int isolationLevel, boolean readOnly, String sql, Object... params) throws NullDataException, SQLException Description copied from interface:DatabaseAccess
Query the database with anIntStream
return type.- Specified by:
intStream
in interfaceDatabaseAccess
- Throws:
NullDataException
- When has a SQL NULL value.SQLException
-
longStream
public LongStream longStream(int isolationLevel, boolean readOnly, String sql, Object... params) throws NullDataException, SQLException Description copied from interface:DatabaseAccess
Query the database with aLongStream
return type.- Specified by:
longStream
in interfaceDatabaseAccess
- Throws:
NullDataException
- When has a SQL NULL value.SQLException
-
stream
public <T,Ex extends Throwable> Stream<T> stream(int isolationLevel, boolean readOnly, Class<? extends Ex> exClass, ObjectFactoryE<? extends T, ? extends Ex> objectFactory, String sql, Object... params) throws SQLException, ExQuery the database with aStream<T>
return type, objects are created with the provided factory.When the factory is nullable, the stream may contain
null
elements. Otherwise, will have the characteristicSpliterator.NONNULL
.- Specified by:
stream
in interfaceDatabaseAccess
- Type Parameters:
Ex
- An arbitrary exception type that may be thrown- Throws:
SQLException
Ex
-
queryCall
public <T,Ex extends Throwable> T queryCall(int isolationLevel, boolean readOnly, Class<? extends Ex> exClass, ResultSetCallableE<? extends T, ? extends Ex> resultSetCallable, String sql, Object... params) throws SQLException, ExQuery the database, calling theResultSetCallableE
once.- Specified by:
queryCall
in interfaceDatabaseAccess
- Type Parameters:
Ex
- An arbitrary exception type that may be thrown- Throws:
SQLException
Ex
-
update
Description copied from interface:DatabaseAccess
Performs an update on the database and returns the number of rows affected.- Specified by:
update
in interfaceDatabaseAccess
- Throws:
SQLException
-
largeUpdate
Description copied from interface:DatabaseAccess
Performs an update on the database and returns the number of rows affected.- Specified by:
largeUpdate
in interfaceDatabaseAccess
- Throws:
SQLException
-
DatabaseConnection
is already within a transaction.