Package org.jdbi.v3.core
Class Handle
- java.lang.Object
-
- org.jdbi.v3.core.Handle
-
- All Implemented Interfaces:
java.io.Closeable,java.lang.AutoCloseable,Configurable<Handle>
public class Handle extends java.lang.Object implements java.io.Closeable, Configurable<Handle>
This represents a connection to the database system. It is a wrapper around a JDBC Connection object. Handle provides essential methods for transaction management, statement creation, and other operations tied to the database session.
-
-
Field Summary
Fields Modifier and Type Field Description private java.util.Set<Cleanable>cleanablesprivate java.util.concurrent.atomic.AtomicBooleanclosedprivate java.sql.Connectionconnectionprivate CleanableconnectionCleanerprivate ExtensionContextcurrentExtensionContextprivate ExtensionContextdefaultExtensionContextprivate booleanforceEndTransactionsprivate java.util.Set<HandleListener>handleListenersprivate Jdbijdbiprivate static org.slf4j.LoggerLOGprivate StatementBuilderstatementBuilderprivate java.util.List<TransactionCallback>transactionCallbacksprivate TransactionHandlertransactionHandler
-
Constructor Summary
Constructors Modifier Constructor Description privateHandle(Jdbi jdbi, Cleanable connectionCleaner, TransactionHandler transactionHandler, StatementBuilder statementBuilder, java.sql.Connection connection)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description (package private) HandleacceptExtensionContext(ExtensionContext extensionContext)voidaddCleanable(Cleanable cleanable)Registers aCleanableto be invoked when the handle is closed.HandleaddHandleListener(HandleListener handleListener)Add a specificHandleListenerwhich is called for specific events for this Handle.(package private) HandleaddTransactionCallback(TransactionCallback cb)HandleafterCommit(java.lang.Runnable afterCommit)Execute an action the next time this Handle commits, unless it is rolled back first.HandleafterRollback(java.lang.Runnable afterRollback)Execute an action the next time this Handle rolls back, unless it is committed first.<T> Tattach(java.lang.Class<T> extensionType)Create a Jdbi extension object of the specified type bound to this handle.Handlebegin()Start a transaction.private booleancheckConnectionIsLive()voidclean()Release any database resource that may be held by the handle.private voidcleanConnection(boolean doForceEndTransactions)voidclose()Closes the handle, its connection, and any other database resources it is holding.Handlecommit()Commit a transaction.BatchcreateBatch()Create a non-prepared (no bound parameters, but different SQL) batch statement.CallcreateCall(java.lang.CharSequence sql)Create a call to a stored procedure.CallcreateCall(java.lang.String sql)Create a call to a stored procedure.(package private) static HandlecreateHandle(Jdbi jdbi, Cleanable connectionCleaner, TransactionHandler transactionHandler, StatementBuilder statementBuilder, java.sql.Connection connection)QuerycreateQuery(java.lang.CharSequence sql)Return a Query instance that executes a statement with bound parameters and maps the result set into Java types.QuerycreateQuery(java.lang.String sql)Return a Query instance that executes a statement with bound parameters and maps the result set into Java types.ScriptcreateScript(java.lang.CharSequence sql)Creates a Script from the given SQL script.ScriptcreateScript(java.lang.String sql)Create an Insert or Update statement which returns the number of rows modified.UpdatecreateUpdate(java.lang.CharSequence sql)Create an Insert or Update statement which returns the number of rows modified.UpdatecreateUpdate(java.lang.String sql)Create an Insert or Update statement which returns the number of rows modified.private voiddoClean(ThrowableSuppressor throwableSuppressor)(package private) java.util.List<TransactionCallback>drainCallbacks()booleanequals(java.lang.Object o)intexecute(java.lang.CharSequence sql, java.lang.Object... args)Execute a SQL statement, and return the number of rows affected by the statement.intexecute(java.lang.String sql, java.lang.Object... args)Execute a SQL statement, and return the number of rows affected by the statement.ConfigRegistrygetConfig()The current configuration object associated with this handle.java.sql.ConnectiongetConnection()Get the JDBCConnectionthis Handle uses.ExtensionMethodgetExtensionMethod()Returns the extension method currently bound to the handle's context.JdbigetJdbi()Returns theJdbiobject used to create this handle.StatementBuildergetStatementBuilder()Returns the currentStatementBuilderwhich is used to create new JDBCStatementobjects.TransactionIsolationLevelgetTransactionIsolationLevel()Obtain the current transaction isolation level.inthashCode()<R,X extends java.lang.Exception>
RinTransaction(HandleCallback<R,X> callback)Executescallbackin a transaction, and returns the result of the callback.<R,X extends java.lang.Exception>
RinTransaction(TransactionIsolationLevel level, HandleCallback<R,X> callback)Executescallbackin a transaction, and returns the result of the callback.booleanisClean()Returns true if the Handle currently holds no database resources.booleanisClosed()Returns true if theHandlehas been closed.booleanisInTransaction()Returns whether the handle is in a transaction.booleanisReadOnly()Whether the connection is in read-only mode.private static longmsSince(long start)private voidnotifyHandleClosed()private voidnotifyHandleCreated()PreparedBatchprepareBatch(java.lang.CharSequence sql)Prepare a batch to execute.PreparedBatchprepareBatch(java.lang.String sql)Prepare a batch to execute.ResultBearingqueryMetadata(MetaData.MetaDataResultSetProvider metadataFunction)Access database metadata that returns aResultSet.<T> TqueryMetadata(MetaData.MetaDataValueProvider<T> metadataFunction)Access all database metadata that returns simple values.Handlerelease(java.lang.String savepointName)Deprecated.HandlereleaseSavepoint(java.lang.String savepointName)Release a previously created savepoint.voidremoveCleanable(Cleanable cleanable)Unregister aCleanablefrom the Handle.HandleremoveHandleListener(HandleListener handleListener)Remove aHandleListenerfrom this handle.Handlerollback()Rollback a transaction.HandlerollbackToSavepoint(java.lang.String savepointName)Rollback a transaction to a named savepoint.Handlesavepoint(java.lang.String name)Create a transaction savepoint with the name provided.Queryselect(java.lang.CharSequence sql, java.lang.Object... args)Convenience method which creates a query with the given positional arguments.Queryselect(java.lang.String sql, java.lang.Object... args)Convenience method which creates a query with the given positional arguments.HandlesetReadOnly(boolean readOnly)Set the Handle read-only.HandlesetStatementBuilder(StatementBuilder builder)Set the statement builder for this handle.voidsetTransactionIsolation(int level)Deprecated.voidsetTransactionIsolation(TransactionIsolationLevel level)Deprecated.voidsetTransactionIsolationLevel(int level)Set the transaction isolation level on the underlying connection if it is different from the current isolation level.voidsetTransactionIsolationLevel(TransactionIsolationLevel level)Set the transaction isolation level on the underlying connection if it is different from the current isolation level.<X extends java.lang.Exception>
voiduseTransaction(HandleConsumer<X> consumer)Executescallbackin a transaction.<X extends java.lang.Exception>
voiduseTransaction(TransactionIsolationLevel level, HandleConsumer<X> consumer)Executescallbackin a transaction.-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface org.jdbi.v3.core.config.Configurable
addCustomizer, configure, define, getConfig, registerArgument, registerArgument, registerArrayType, registerArrayType, registerArrayType, registerArrayType, registerCodecFactory, registerCollector, registerCollector, registerColumnMapper, registerColumnMapper, registerColumnMapper, registerColumnMapper, registerColumnMapper, registerColumnMapper, registerExtension, registerRowMapper, registerRowMapper, registerRowMapper, registerRowMapper, setMapKeyColumn, setMapValueColumn, setSqlArrayArgumentStrategy, setSqlLogger, setSqlParser, setTemplateEngine, setTimingCollector
-
-
-
-
Field Detail
-
LOG
private static final org.slf4j.Logger LOG
-
jdbi
private final Jdbi jdbi
-
connectionCleaner
private final Cleanable connectionCleaner
-
transactionHandler
private final TransactionHandler transactionHandler
-
connection
private final java.sql.Connection connection
-
forceEndTransactions
private final boolean forceEndTransactions
-
statementBuilder
private StatementBuilder statementBuilder
-
defaultExtensionContext
private final ExtensionContext defaultExtensionContext
-
currentExtensionContext
private ExtensionContext currentExtensionContext
-
transactionCallbacks
private final java.util.List<TransactionCallback> transactionCallbacks
-
cleanables
private final java.util.Set<Cleanable> cleanables
-
handleListeners
private final java.util.Set<HandleListener> handleListeners
-
closed
private final java.util.concurrent.atomic.AtomicBoolean closed
-
-
Constructor Detail
-
Handle
private Handle(Jdbi jdbi, Cleanable connectionCleaner, TransactionHandler transactionHandler, StatementBuilder statementBuilder, java.sql.Connection connection) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
-
Method Detail
-
createHandle
static Handle createHandle(Jdbi jdbi, Cleanable connectionCleaner, TransactionHandler transactionHandler, StatementBuilder statementBuilder, java.sql.Connection connection) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
getJdbi
public Jdbi getJdbi()
Returns theJdbiobject used to create this handle.- Returns:
- The
Jdbiobject used to create this handle.
-
getConfig
public ConfigRegistry getConfig()
The current configuration object associated with this handle.- Specified by:
getConfigin interfaceConfigurable<Handle>- Returns:
- A
ConfigRegistryobject that is associated with the handle.
-
getConnection
public java.sql.Connection getConnection()
Get the JDBCConnectionthis Handle uses.- Returns:
- the JDBC
Connectionthis Handle uses.
-
getStatementBuilder
public StatementBuilder getStatementBuilder()
Returns the currentStatementBuilderwhich is used to create new JDBCStatementobjects.- Returns:
- the current
StatementBuilder.
-
setStatementBuilder
public Handle setStatementBuilder(StatementBuilder builder)
Set the statement builder for this handle.- Parameters:
builder- StatementBuilder to be used. Must not be null.- Returns:
- this
-
addHandleListener
public Handle addHandleListener(HandleListener handleListener)
Add a specificHandleListenerwhich is called for specific events for this Handle. Note that it is not possible to add a listener that wants to implementHandleListener.handleCreated(org.jdbi.v3.core.Handle)this way as the handle has already been created. UseHandles.addListener(org.jdbi.v3.core.HandleListener)in this case.
A listener added through this call is specific to the handle and not shared with other handles.- Parameters:
handleListener- AHandleListenerobject.- Returns:
- The handle itself.
-
removeHandleListener
public Handle removeHandleListener(HandleListener handleListener)
Remove aHandleListenerfrom this handle.
Removing the listener only affects the current handle. To remove a listener for all future handles, useHandles.removeListener(org.jdbi.v3.core.HandleListener).- Parameters:
handleListener- AHandleListenerobject.- Returns:
- The handle itself.
-
addCleanable
public final void addCleanable(Cleanable cleanable)
Registers aCleanableto be invoked when the handle is closed. Any cleanable registered here will only be cleaned once.Resources cleaned up by Jdbi include
ResultSet,Statement,Array, andStatementBuilder.- Parameters:
cleanable- the Cleanable to clean on close
-
removeCleanable
public final void removeCleanable(Cleanable cleanable)
Unregister aCleanablefrom the Handle.- Parameters:
cleanable- the Cleanable to be unregistered.
-
close
public void close()
Closes the handle, its connection, and any other database resources it is holding.- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable- Throws:
CloseException- if any resources throw exception while closingTransactionException- if called while the handle has a transaction open. The open transaction will be rolled back.
-
clean
public void clean()
Release any database resource that may be held by the handle. This affects any statement that was created from the Handle.
-
isClean
public boolean isClean()
Returns true if the Handle currently holds no database resources.
Note that this method will returnfalseright after statement creation as every statement registers its statement context with the handle. Once- Returns:
- True if the handle holds no database resources.
-
doClean
private void doClean(ThrowableSuppressor throwableSuppressor)
-
isClosed
public boolean isClosed()
Returns true if theHandlehas been closed.- Returns:
- True if the Handle is closed.
-
select
public Query select(java.lang.CharSequence sql, java.lang.Object... args)
Convenience method which creates a query with the given positional arguments.- Parameters:
sql- SQL or named statementargs- arguments to bind positionally- Returns:
- query object
-
select
public Query select(java.lang.String sql, java.lang.Object... args)
Convenience method which creates a query with the given positional arguments. Takes a string argument for backwards compatibility reasons.- Parameters:
sql- SQL or named statementargs- arguments to bind positionally- Returns:
- query object
- See Also:
select(CharSequence, Object...)
-
execute
public int execute(java.lang.CharSequence sql, java.lang.Object... args)Execute a SQL statement, and return the number of rows affected by the statement.- Parameters:
sql- the SQL statement to execute, using positional parameters (if any).args- positional arguments.- Returns:
- the number of rows affected.
-
execute
public int execute(java.lang.String sql, java.lang.Object... args)Execute a SQL statement, and return the number of rows affected by the statement. Takes a string argument for backwards compatibility reasons.- Parameters:
sql- the SQL statement to execute, using positional parameters (if any).args- positional arguments.- Returns:
- the number of rows affected.
- See Also:
execute(CharSequence, Object...)
-
createBatch
public Batch createBatch()
Create a non-prepared (no bound parameters, but different SQL) batch statement.- Returns:
- empty batch
- See Also:
prepareBatch(String)
-
prepareBatch
public PreparedBatch prepareBatch(java.lang.CharSequence sql)
Prepare a batch to execute. This is for efficiently executing more than one of the same statements with different parameters bound.- Parameters:
sql- the batch SQL.- Returns:
- a batch which can have "statements" added.
-
prepareBatch
public PreparedBatch prepareBatch(java.lang.String sql)
Prepare a batch to execute. This is for efficiently executing more than one of the same statements with different parameters bound. Takes a string argument for backwards compatibility reasons.- Parameters:
sql- the batch SQL.- Returns:
- a batch which can have "statements" added.
- See Also:
prepareBatch(CharSequence)
-
createCall
public Call createCall(java.lang.CharSequence sql)
Create a call to a stored procedure.- Parameters:
sql- the stored procedure sql.- Returns:
- the Call.
-
createCall
public Call createCall(java.lang.String sql)
Create a call to a stored procedure. Takes a string argument for backwards compatibility reasons.- Parameters:
sql- the stored procedure sql.- Returns:
- the Call.
- See Also:
createCall(CharSequence)
-
createQuery
public Query createQuery(java.lang.CharSequence sql)
Return a Query instance that executes a statement with bound parameters and maps the result set into Java types.- Parameters:
sql- SQL that may return results.- Returns:
- a Query builder.
-
createQuery
public Query createQuery(java.lang.String sql)
Return a Query instance that executes a statement with bound parameters and maps the result set into Java types. Takes a string argument for backwards compatibility reasons.- Parameters:
sql- SQL that may return results.- Returns:
- a Query builder.
- See Also:
createQuery(CharSequence)
-
createScript
public Script createScript(java.lang.CharSequence sql)
Creates a Script from the given SQL script.- Parameters:
sql- the SQL script.- Returns:
- the created Script.
-
createScript
public Script createScript(java.lang.String sql)
Create an Insert or Update statement which returns the number of rows modified. Takes a string argument for backwards compatibility reasons.- Parameters:
sql- the statement sql.- Returns:
- the Update builder.
- See Also:
createScript(CharSequence)
-
createUpdate
public Update createUpdate(java.lang.CharSequence sql)
Create an Insert or Update statement which returns the number of rows modified.- Parameters:
sql- the statement sql.- Returns:
- the Update builder.
-
createUpdate
public Update createUpdate(java.lang.String sql)
Create an Insert or Update statement which returns the number of rows modified. Takes a string argument for backwards compatibility reasons.- Parameters:
sql- the statement sql.- Returns:
- the Update builder.
- See Also:
createUpdate(CharSequence)
-
queryMetadata
public ResultBearing queryMetadata(MetaData.MetaDataResultSetProvider metadataFunction)
Access database metadata that returns aResultSet. All methods ofResultBearingcan be used to format and map the returned results.List<String> catalogs = h.queryMetadata(DatabaseMetaData::getCatalogs) .mapTo(String.class) .list();returns the list of catalogs from the current database.
- Parameters:
metadataFunction- Maps the providedDatabaseMetaDataobject onto aResultSetobject.- Returns:
- The metadata builder.
-
queryMetadata
public <T> T queryMetadata(MetaData.MetaDataValueProvider<T> metadataFunction)
Access all database metadata that returns simple values.boolean supportsTransactions = handle.queryMetadata(DatabaseMetaData::supportsTransactions);- Parameters:
metadataFunction- Maps the providedDatabaseMetaDataobject to a response object.- Returns:
- The response object.
-
isInTransaction
public boolean isInTransaction()
Returns whether the handle is in a transaction. Delegates to the underlyingTransactionHandler.- Returns:
- True if the handle is in a transaction.
-
begin
public Handle begin()
Start a transaction.- Returns:
- the same handle.
-
commit
public Handle commit()
Commit a transaction.- Returns:
- the same handle.
-
rollback
public Handle rollback()
Rollback a transaction.- Returns:
- the same handle.
-
afterCommit
@Beta public Handle afterCommit(java.lang.Runnable afterCommit)
Execute an action the next time this Handle commits, unless it is rolled back first.- Parameters:
afterCommit- the action to execute after commit.- Returns:
- this Handle.
-
afterRollback
@Beta public Handle afterRollback(java.lang.Runnable afterRollback)
Execute an action the next time this Handle rolls back, unless it is committed first.- Parameters:
afterRollback- the action to execute after rollback.- Returns:
- this Handle.
-
drainCallbacks
java.util.List<TransactionCallback> drainCallbacks()
-
addTransactionCallback
Handle addTransactionCallback(TransactionCallback cb)
-
rollbackToSavepoint
public Handle rollbackToSavepoint(java.lang.String savepointName)
Rollback a transaction to a named savepoint.- Parameters:
savepointName- the name of the savepoint, previously declared withsavepoint(java.lang.String).- Returns:
- the same handle.
-
msSince
private static long msSince(long start)
-
savepoint
public Handle savepoint(java.lang.String name)
Create a transaction savepoint with the name provided.- Parameters:
name- The name of the savepoint.- Returns:
- The same handle.
-
release
@Deprecated public Handle release(java.lang.String savepointName)
Deprecated.Release a previously created savepoint.- Parameters:
savepointName- the name of the savepoint to release.- Returns:
- the same handle.
-
releaseSavepoint
public Handle releaseSavepoint(java.lang.String savepointName)
Release a previously created savepoint.- Parameters:
savepointName- the name of the savepoint to release.- Returns:
- the same handle.
-
isReadOnly
public boolean isReadOnly()
Whether the connection is in read-only mode.- Returns:
- True if the connection is in read-only mode.
- See Also:
Connection.isReadOnly()
-
setReadOnly
public Handle setReadOnly(boolean readOnly)
Set the Handle read-only. This acts as a hint to the database to improve performance or concurrency.
May not be called in an active transaction!- Parameters:
readOnly- whether the Handle is readOnly.- Returns:
- this Handle.
- See Also:
Connection.setReadOnly(boolean)
-
inTransaction
public <R,X extends java.lang.Exception> R inTransaction(HandleCallback<R,X> callback) throws X extends java.lang.Exception
Executescallbackin a transaction, and returns the result of the callback.- Type Parameters:
R- type returned by callbackX- exception type thrown by the callback, if any- Parameters:
callback- a callback which will receive an open handle, in a transaction.- Returns:
- value returned from the callback
- Throws:
X- any exception thrown by the callbackX extends java.lang.Exception
-
useTransaction
public <X extends java.lang.Exception> void useTransaction(HandleConsumer<X> consumer) throws X extends java.lang.Exception
Executescallbackin a transaction.- Type Parameters:
X- exception type thrown by the callback, if any- Parameters:
consumer- a callback which will receive an open handle, in a transaction.- Throws:
X- any exception thrown by the callbackX extends java.lang.Exception
-
inTransaction
public <R,X extends java.lang.Exception> R inTransaction(TransactionIsolationLevel level, HandleCallback<R,X> callback) throws X extends java.lang.Exception
Executescallbackin a transaction, and returns the result of the callback.This form accepts a transaction isolation level which will be applied to the connection for the scope of this transaction, after which the original isolation level will be restored.
- Type Parameters:
R- type returned by callbackX- exception type thrown by the callback, if any- Parameters:
level- the transaction isolation level which will be applied to the connection for the scope of this transaction, after which the original isolation level will be restored.callback- a callback which will receive an open handle, in a transaction.- Returns:
- value returned from the callback
- Throws:
X- any exception thrown by the callbackX extends java.lang.Exception
-
useTransaction
public <X extends java.lang.Exception> void useTransaction(TransactionIsolationLevel level, HandleConsumer<X> consumer) throws X extends java.lang.Exception
Executescallbackin a transaction.This form accepts a transaction isolation level which will be applied to the connection for the scope of this transaction, after which the original isolation level will be restored.
- Type Parameters:
X- exception type thrown by the callback, if any- Parameters:
level- the transaction isolation level which will be applied to the connection for the scope of this transaction, after which the original isolation level will be restored.consumer- a callback which will receive an open handle, in a transaction.- Throws:
X- any exception thrown by the callbackX extends java.lang.Exception
-
setTransactionIsolation
@Deprecated public void setTransactionIsolation(TransactionIsolationLevel level)
Deprecated.Set the transaction isolation level on the underlying connection if it is different from the current isolation level.- Parameters:
level- theTransactionIsolationLevelto use.- Throws:
UnableToManipulateTransactionIsolationLevelException- if isolation level is not supported by the underlying connection or JDBC driver.
-
setTransactionIsolationLevel
public void setTransactionIsolationLevel(TransactionIsolationLevel level)
Set the transaction isolation level on the underlying connection if it is different from the current isolation level.- Parameters:
level- theTransactionIsolationLevelto use.- Throws:
UnableToManipulateTransactionIsolationLevelException- if isolation level is not supported by the underlying connection or JDBC driver.
-
setTransactionIsolation
@Deprecated public void setTransactionIsolation(int level)
Deprecated.Set the transaction isolation level on the underlying connection if it is different from the current isolation level.- Parameters:
level- the isolation level to use.- See Also:
setTransactionIsolationLevel(TransactionIsolationLevel),Connection.TRANSACTION_NONE,Connection.TRANSACTION_READ_UNCOMMITTED,Connection.TRANSACTION_READ_COMMITTED,Connection.TRANSACTION_REPEATABLE_READ,Connection.TRANSACTION_SERIALIZABLE
-
setTransactionIsolationLevel
public void setTransactionIsolationLevel(int level)
Set the transaction isolation level on the underlying connection if it is different from the current isolation level.- Parameters:
level- the isolation level to use.- See Also:
setTransactionIsolationLevel(TransactionIsolationLevel),Connection.TRANSACTION_NONE,Connection.TRANSACTION_READ_UNCOMMITTED,Connection.TRANSACTION_READ_COMMITTED,Connection.TRANSACTION_REPEATABLE_READ,Connection.TRANSACTION_SERIALIZABLE
-
getTransactionIsolationLevel
public TransactionIsolationLevel getTransactionIsolationLevel()
Obtain the current transaction isolation level.- Returns:
- the current isolation level on the underlying connection.
-
attach
public <T> T attach(java.lang.Class<T> extensionType)
Create a Jdbi extension object of the specified type bound to this handle. The returned extension's lifecycle is coupled to the lifecycle of this handle. Closing the handle will render the extension unusable.- Type Parameters:
T- the extension type- Parameters:
extensionType- the extension class- Returns:
- the new extension object bound to this handle
-
getExtensionMethod
public ExtensionMethod getExtensionMethod()
Returns the extension method currently bound to the handle's context.- Returns:
- the extension method currently bound to the handle's context
-
acceptExtensionContext
Handle acceptExtensionContext(ExtensionContext extensionContext)
-
notifyHandleCreated
private void notifyHandleCreated()
-
notifyHandleClosed
private void notifyHandleClosed()
-
cleanConnection
private void cleanConnection(boolean doForceEndTransactions)
-
checkConnectionIsLive
private boolean checkConnectionIsLive()
-
equals
public boolean equals(java.lang.Object o)
- Overrides:
equalsin classjava.lang.Object
-
hashCode
public int hashCode()
- Overrides:
hashCodein classjava.lang.Object
-
-