Class AbstractSynchronousTransactionManager<T>
- Type Parameters:
T
- The resource type
- All Implemented Interfaces:
TransactionStateOperations<T,
,SynchronousTransactionState> SynchronousTransactionManager<T>
,TransactionManager
,TransactionOperations<T>
,Serializable
- Direct Known Subclasses:
DataSourceTransactionManager
,HibernateTransactionManager
,MongoSynchronousTransactionManagerImpl
AbstractPlatformTransactionManager
modernizing it
to use enums, Slf4j and decoupling from Spring.
Abstract base class that implements standard transaction workflow,
serving as basis for concrete platform transaction managers.
This base class provides the following workflow handling:
- determines if there is an existing transaction;
- applies the appropriate propagation behavior;
- suspends and resumes transactions if necessary;
- checks the rollback-only flag on commit;
- applies the appropriate modification on rollback (actual rollback or setting rollback-only);
- triggers registered synchronization callbacks (if transaction synchronization is active).
Subclasses have to implement specific template methods for specific states of a transaction, e.g.: begin, suspend, resume, commit, rollback. The most important of them are abstract and must be provided by a concrete implementation; for the rest, defaults are provided, so overriding is optional.
Transaction synchronization is a generic mechanism for registering callbacks that get invoked at transaction completion time. This is mainly used internally by the data access support classes for JDBC, Hibernate, JPA, etc when running within a JTA transaction: They register resources that are opened within the transaction for closing at transaction completion time, allowing e.g. for reuse of the same Hibernate Session within the transaction. The same mechanism can also be leveraged for custom synchronization needs in an application.
The state of this class is serializable, to allow for serializing the
transaction strategy along with proxies that carry a transaction interceptor.
It is up to subclasses if they wish to make their state to be serializable too.
They should implement the java.io.Serializable
marker interface in
that case, and potentially a private readObject()
method (according
to Java serialization rules) if they need to restore any transient state.
- Since:
- 28.03.2003
- Author:
- Juergen Hoeller, graemerocher
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static final class
Holder for suspended resources. -
Field Summary
Fields inherited from class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager
logger
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal void
commit
(TransactionStatus<T> status) This implementation of commit handles participating in existing transactions and programmatic rollback requests.protected void
doCleanupAfterCompletion
(SynchronousTransactionState state, Object transaction) Cleanup resources after transaction completion.protected void
doCleanupAfterCompletion
(Object transaction) Cleanup resources after transaction completion.protected void
Destroy the state.protected abstract Object
Return a transaction object for the current transaction state.protected Object
Return a transaction object for the current transaction state.<R> R
execute
(TransactionDefinition definition, TransactionCallback<T, R> callback) Execute a transaction within the context of the function.<R> R
executeRead
(TransactionCallback<T, R> callback) Execute a read-only transaction within the context of the function.<R> R
executeWrite
(TransactionCallback<T, R> callback) Execute a default transaction within the context of the function.find()
Find optional transaction state.protected SynchronousTransactionState
Find or create a new state.protected T
getConnection
(SynchronousTransactionState state, Object transaction) The connection for the given transaction object.protected abstract T
getConnection
(Object transaction) The connection for the given transaction object.protected SynchronousTransactionState
getState()
Return required current transaction state.final TransactionStatus<T>
getTransaction
(TransactionDefinition definition) Return a currently active transaction or create a new one, according to the specified propagation behavior.protected Object
Get the transaction state key that should be used to store the state.protected final void
invokeAfterCompletion
(List<TransactionSynchronization> synchronizations, TransactionSynchronization.Status completionStatus) Actually invoke theafterCompletion
methods of the given Spring TransactionSynchronization objects.protected boolean
isExistingTransaction
(SynchronousTransactionState state, Object transaction) Check if the given transaction object indicates an existing transaction (that is, a transaction which has already started).protected boolean
isExistingTransaction
(Object transaction) Check if the given transaction object indicates an existing transaction (that is, a transaction which has already started).protected DefaultTransactionStatus<T>
newTransactionStatus
(SynchronousTransactionState state, TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources) Create a TransactionStatus instance for the given arguments.protected DefaultTransactionStatus<T>
newTransactionStatus
(TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources) Create a TransactionStatus instance for the given arguments.protected void
prepareSynchronization
(DefaultTransactionStatus<T> status, TransactionDefinition definition) Initialize transaction synchronization as appropriate.protected void
prepareSynchronization
(SynchronousTransactionState state, DefaultTransactionStatus<T> status, TransactionDefinition definition) Initialize transaction synchronization as appropriate.protected final DefaultTransactionStatus<T>
prepareTransactionStatus
(TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources) Create a new TransactionStatus for the given arguments, also initializing transaction synchronization as appropriate.protected void
registerAfterCompletionWithExistingTransaction
(SynchronousTransactionState state, Object transaction, List<TransactionSynchronization> synchronizations) Register the given list of transaction synchronizations with the existing transaction.protected void
registerAfterCompletionWithExistingTransaction
(Object transaction, List<TransactionSynchronization> synchronizations) Register the given list of transaction synchronizations with the existing transaction.protected final void
resume
(Object transaction, AbstractSynchronousTransactionManager.SuspendedResourcesHolder resourcesHolder) Resume the given transaction.final void
rollback
(TransactionStatus<T> status) This implementation of rollback handles participating in existing transactions.protected final AbstractSynchronousTransactionManager.SuspendedResourcesHolder
Suspend the given transaction.protected final void
triggerBeforeCommit
(DefaultTransactionStatus<T> status) TriggerbeforeCommit
callbacks.protected final void
TriggerbeforeCompletion
callbacks.Methods inherited from class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager
commit, determineTimeout, doBegin, doCommit, doResume, doRollback, doSetRollbackOnly, doSuspend, execute, executeRead, executeWrite, getDefaultTimeout, getTransaction, getTransactionSynchronization, invokeAfterCompletion, isFailEarlyOnGlobalRollbackOnly, isGlobalRollbackOnParticipationFailure, isNestedTransactionAllowed, isRollbackOnCommitFailure, isValidateExistingTransaction, prepareForCommit, prepareTransactionStatus, resume, rollback, setDefaultTimeout, setFailEarlyOnGlobalRollbackOnly, setGlobalRollbackOnParticipationFailure, setNestedTransactionAllowed, setRollbackOnCommitFailure, setTransactionSynchronization, setValidateExistingTransaction, shouldCommitOnGlobalRollbackOnly, suspend, triggerBeforeCommit, triggerBeforeCompletion, useSavepointForNestedTransaction
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface io.micronaut.transaction.TransactionOperations
getConnection, hasConnection
-
Constructor Details
-
AbstractSynchronousTransactionManager
public AbstractSynchronousTransactionManager()
-
-
Method Details
-
getTransactionStateKey
Get the transaction state key that should be used to store the state.- Returns:
- The key
-
getState
Return required current transaction state.- Returns:
- The state
-
findOrCreateState
Find or create a new state.- Returns:
- The state
-
find
Find optional transaction state.- Returns:
- The state
-
doDestroyState
Destroy the state.- Overrides:
doDestroyState
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The state
-
execute
public <R> R execute(@NonNull TransactionDefinition definition, @NonNull TransactionCallback<T, R> callback) Description copied from interface:TransactionOperations
Execute a transaction within the context of the function.- Specified by:
execute
in interfaceTransactionOperations<T>
- Type Parameters:
R
- The result- Parameters:
definition
- The transaction definitioncallback
- The call back- Returns:
- The result
-
executeRead
Description copied from interface:TransactionOperations
Execute a read-only transaction within the context of the function.- Specified by:
executeRead
in interfaceTransactionOperations<T>
- Type Parameters:
R
- The result- Parameters:
callback
- The call back- Returns:
- The result
-
executeWrite
Description copied from interface:TransactionOperations
Execute a default transaction within the context of the function.- Specified by:
executeWrite
in interfaceTransactionOperations<T>
- Type Parameters:
R
- The result- Parameters:
callback
- The call back- Returns:
- The result
-
getTransaction
@NonNull public final TransactionStatus<T> getTransaction(@Nullable TransactionDefinition definition) throws TransactionException Description copied from interface:SynchronousTransactionManager
Return a currently active transaction or create a new one, according to the specified propagation behavior.Note that parameters like isolation level or timeout will only be applied to new transactions, and thus be ignored when participating in active ones.
Furthermore, not all transaction definition settings will be supported by every transaction manager: A proper transaction manager implementation should throw an exception when unsupported settings are encountered.
An exception to the above rule is the read-only flag, which should be ignored if no explicit read-only mode is supported. Essentially, the read-only flag is just a hint for potential optimization.
- Specified by:
getTransaction
in interfaceSynchronousTransactionManager<T>
- Parameters:
definition
- the TransactionDefinition instance (can benull
for defaults), describing propagation behavior, isolation level, timeout etc.- Returns:
- transaction status object representing the new or current transaction
- Throws:
TransactionException
- in case of lookup, creation, or system errorsIllegalTransactionStateException
- if the given transaction definition cannot be executed (for example, if a currently active transaction is in conflict with the specified propagation behavior)- See Also:
-
prepareTransactionStatus
protected final DefaultTransactionStatus<T> prepareTransactionStatus(TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) Create a new TransactionStatus for the given arguments, also initializing transaction synchronization as appropriate.- Parameters:
definition
- The definitiontransaction
- The transaction objectnewTransaction
- Is this is a new transactionnewSynchronization
- Is this a new synchronizationdebug
- Is debug enabledsuspendedResources
- Any suspended resources- Returns:
- The status
- See Also:
-
newTransactionStatus(io.micronaut.transaction.support.SynchronousTransactionState, io.micronaut.transaction.TransactionDefinition, java.lang.Object, boolean, boolean, boolean, java.lang.Object)
prepareTransactionStatus(io.micronaut.transaction.TransactionDefinition, java.lang.Object, boolean, boolean, boolean, java.lang.Object)
-
newTransactionStatus
protected DefaultTransactionStatus<T> newTransactionStatus(SynchronousTransactionState state, TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources) Description copied from class:AbstractSynchronousStateTransactionManager
Create a TransactionStatus instance for the given arguments.- Overrides:
newTransactionStatus
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The transaction statedefinition
- The definitiontransaction
- The transaction objectnewTransaction
- Is this is a new transactionnewSynchronization
- Is this a new synchronizationdebug
- Is debug enabledsuspendedResources
- Any suspended resources- Returns:
- The status
-
newTransactionStatus
protected DefaultTransactionStatus<T> newTransactionStatus(TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) Create a TransactionStatus instance for the given arguments.- Parameters:
definition
- The definitiontransaction
- The transaction objectnewTransaction
- Is this is a new transactionnewSynchronization
- Is this a new synchronizationdebug
- Is debug enabledsuspendedResources
- Any suspended resources- Returns:
- The status
-
getConnection
Description copied from class:AbstractSynchronousStateTransactionManager
The connection for the given transaction object.- Specified by:
getConnection
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The transaction statetransaction
- The transaction- Returns:
- The connection.
-
getConnection
The connection for the given transaction object.- Parameters:
transaction
- The transaction- Returns:
- The connection.
-
prepareSynchronization
protected void prepareSynchronization(SynchronousTransactionState state, DefaultTransactionStatus<T> status, TransactionDefinition definition) Description copied from class:AbstractSynchronousStateTransactionManager
Initialize transaction synchronization as appropriate.- Overrides:
prepareSynchronization
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The transaction statestatus
- The statusdefinition
- The definition
-
prepareSynchronization
protected void prepareSynchronization(@NonNull DefaultTransactionStatus<T> status, @NonNull TransactionDefinition definition) Initialize transaction synchronization as appropriate.- Parameters:
status
- The statusdefinition
- The definition
-
suspend
@Nullable protected final AbstractSynchronousTransactionManager.SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException Suspend the given transaction. Suspends transaction synchronization first, then delegates to thedoSuspend
template method.- Parameters:
transaction
- the current transaction object (ornull
to just suspend active synchronizations, if any)- Returns:
- an object that holds suspended resources
(or
null
if neither transaction nor synchronization active) - Throws:
TransactionException
- Thrown if an error occurs suspending the transaction- See Also:
-
resume
protected final void resume(@Nullable Object transaction, @Nullable AbstractSynchronousTransactionManager.SuspendedResourcesHolder resourcesHolder) throws TransactionException Resume the given transaction. Delegates to thedoResume
template method first, then resuming transaction synchronization.- Parameters:
transaction
- the current transaction objectresourcesHolder
- the object that holds suspended resources, as returned bysuspend
(ornull
to just resume synchronizations, if any)- Throws:
TransactionException
- Thrown if an error occurs resuming the transaction- See Also:
-
commit
This implementation of commit handles participating in existing transactions and programmatic rollback requests. Delegates toisRollbackOnly
,doCommit
androllback
.- Specified by:
commit
in interfaceSynchronousTransactionManager<T>
- Parameters:
status
- object returned by thegetTransaction
method- Throws:
UnexpectedRollbackException
- in case of an unexpected rollback that the transaction coordinator initiatedHeuristicCompletionException
- in case of a transaction failure caused by a heuristic decision on the side of the transaction coordinatorTransactionSystemException
- in case of commit or system errors (typically caused by fundamental resource failures)IllegalTransactionStateException
- if the given transaction is already completed (that is, committed or rolled back)TransactionException
- if something goes wrong during commit- See Also:
-
rollback
This implementation of rollback handles participating in existing transactions. Delegates todoRollback
anddoSetRollbackOnly
.- Specified by:
rollback
in interfaceSynchronousTransactionManager<T>
- Parameters:
status
- object returned by thegetTransaction
method- Throws:
TransactionSystemException
- in case of rollback or system errors (typically caused by fundamental resource failures)IllegalTransactionStateException
- if the given transaction is already completed (that is, committed or rolled back)TransactionException
- if something goes wrong during rollback- See Also:
-
triggerBeforeCommit
TriggerbeforeCommit
callbacks.- Parameters:
status
- object representing the transaction
-
triggerBeforeCompletion
TriggerbeforeCompletion
callbacks.- Parameters:
status
- object representing the transaction
-
doGetTransaction
protected Object doGetTransaction(@NonNull SynchronousTransactionState state) throws TransactionException Description copied from class:AbstractSynchronousStateTransactionManager
Return a transaction object for the current transaction state.The returned object will usually be specific to the concrete transaction manager implementation, carrying corresponding transaction state in a modifiable fashion. This object will be passed into the other template methods (e.g. doBegin and doCommit), either directly or as part of a DefaultTransactionStatus instance.
The returned object should contain information about any existing transaction, that is, a transaction that has already started before the current
getTransaction
call on the transaction manager. Consequently, adoGetTransaction
implementation will usually look for an existing transaction and store corresponding state in the returned transaction object.- Specified by:
doGetTransaction
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The transaction state- Returns:
- the current transaction object
- Throws:
CannotCreateTransactionException
- if transaction support is not availableTransactionException
- in case of lookup or system errors- See Also:
-
AbstractSynchronousStateTransactionManager.doBegin(java.lang.Object, io.micronaut.transaction.TransactionDefinition)
AbstractSynchronousStateTransactionManager.doCommit(io.micronaut.transaction.support.DefaultTransactionStatus<T>)
AbstractSynchronousStateTransactionManager.doRollback(io.micronaut.transaction.support.DefaultTransactionStatus<T>)
DefaultTransactionStatus.getTransaction()
-
isExistingTransaction
protected boolean isExistingTransaction(@NonNull SynchronousTransactionState state, @NonNull Object transaction) throws TransactionException Description copied from class:AbstractSynchronousStateTransactionManager
Check if the given transaction object indicates an existing transaction (that is, a transaction which has already started).The result will be evaluated according to the specified propagation behavior for the new transaction. An existing transaction might get suspended (in case of PROPAGATION_REQUIRES_NEW), or the new transaction might participate in the existing one (in case of PROPAGATION_REQUIRED).
The default implementation returns
false
, assuming that participating in existing transactions is generally not supported. Subclasses are of course encouraged to provide such support.- Overrides:
isExistingTransaction
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The transaction statetransaction
- transaction object returned by doGetTransaction- Returns:
- if there is an existing transaction
- Throws:
TransactionException
- in case of system errors- See Also:
-
invokeAfterCompletion
protected final void invokeAfterCompletion(List<TransactionSynchronization> synchronizations, TransactionSynchronization.Status completionStatus) Actually invoke theafterCompletion
methods of the given Spring TransactionSynchronization objects.To be called by this abstract manager itself, or by special implementations of the
registerAfterCompletionWithExistingTransaction
callback.- Parameters:
synchronizations
- a List of TransactionSynchronization objectscompletionStatus
- the completion status according to the constants in the TransactionSynchronization interface- See Also:
-
doGetTransaction
Return a transaction object for the current transaction state.The returned object will usually be specific to the concrete transaction manager implementation, carrying corresponding transaction state in a modifiable fashion. This object will be passed into the other template methods (e.g. doBegin and doCommit), either directly or as part of a DefaultTransactionStatus instance.
The returned object should contain information about any existing transaction, that is, a transaction that has already started before the current
getTransaction
call on the transaction manager. Consequently, adoGetTransaction
implementation will usually look for an existing transaction and store corresponding state in the returned transaction object.- Returns:
- the current transaction object
- Throws:
CannotCreateTransactionException
- if transaction support is not availableTransactionException
- in case of lookup or system errors- See Also:
-
AbstractSynchronousStateTransactionManager.doBegin(java.lang.Object, io.micronaut.transaction.TransactionDefinition)
AbstractSynchronousStateTransactionManager.doCommit(io.micronaut.transaction.support.DefaultTransactionStatus<T>)
AbstractSynchronousStateTransactionManager.doRollback(io.micronaut.transaction.support.DefaultTransactionStatus<T>)
DefaultTransactionStatus.getTransaction()
-
isExistingTransaction
Check if the given transaction object indicates an existing transaction (that is, a transaction which has already started).The result will be evaluated according to the specified propagation behavior for the new transaction. An existing transaction might get suspended (in case of PROPAGATION_REQUIRES_NEW), or the new transaction might participate in the existing one (in case of PROPAGATION_REQUIRED).
The default implementation returns
false
, assuming that participating in existing transactions is generally not supported. Subclasses are of course encouraged to provide such support.- Parameters:
transaction
- transaction object returned by doGetTransaction- Returns:
- if there is an existing transaction
- Throws:
TransactionException
- in case of system errors- See Also:
-
registerAfterCompletionWithExistingTransaction
protected void registerAfterCompletionWithExistingTransaction(SynchronousTransactionState state, Object transaction, List<TransactionSynchronization> synchronizations) throws TransactionException Description copied from class:AbstractSynchronousStateTransactionManager
Register the given list of transaction synchronizations with the existing transaction.Invoked when the control of the transaction manager and thus all transaction synchronizations end, without the transaction being completed yet. This is for example the case when participating in an existing JTA or EJB CMT transaction.
The default implementation simply invokes the
afterCompletion
methods immediately, passing in "STATUS_UNKNOWN". This is the best we can do if there's no chance to determine the actual outcome of the outer transaction.- Overrides:
registerAfterCompletionWithExistingTransaction
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The transaction statetransaction
- transaction object returned bydoGetTransaction
synchronizations
- a List of TransactionSynchronization objects- Throws:
TransactionException
- in case of system errors- See Also:
-
registerAfterCompletionWithExistingTransaction
protected void registerAfterCompletionWithExistingTransaction(Object transaction, List<TransactionSynchronization> synchronizations) throws TransactionException Register the given list of transaction synchronizations with the existing transaction.Invoked when the control of the Spring transaction manager and thus all Spring transaction synchronizations end, without the transaction being completed yet. This is for example the case when participating in an existing JTA or EJB CMT transaction.
The default implementation simply invokes the
afterCompletion
methods immediately, passing in "STATUS_UNKNOWN". This is the best we can do if there's no chance to determine the actual outcome of the outer transaction.- Parameters:
transaction
- transaction object returned bydoGetTransaction
synchronizations
- a List of TransactionSynchronization objects- Throws:
TransactionException
- in case of system errors- See Also:
-
doCleanupAfterCompletion
Description copied from class:AbstractSynchronousStateTransactionManager
Cleanup resources after transaction completion.Called after
doCommit
anddoRollback
execution, on any outcome. The default implementation does nothing.Should not throw any exceptions but just issue warnings on errors.
- Overrides:
doCleanupAfterCompletion
in classAbstractSynchronousStateTransactionManager<T>
- Parameters:
state
- The statetransaction
- transaction object returned bydoGetTransaction
-
doCleanupAfterCompletion
Cleanup resources after transaction completion.Called after
doCommit
anddoRollback
execution, on any outcome. The default implementation does nothing.Should not throw any exceptions but just issue warnings on errors.
- Parameters:
transaction
- transaction object returned bydoGetTransaction
-