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 classHolder for suspended resources. -
Field Summary
Fields inherited from class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager
logger -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal voidcommit(TransactionStatus<T> status) This implementation of commit handles participating in existing transactions and programmatic rollback requests.protected voiddoCleanupAfterCompletion(SynchronousTransactionState state, Object transaction) Cleanup resources after transaction completion.protected voiddoCleanupAfterCompletion(Object transaction) Cleanup resources after transaction completion.protected voidDestroy the state.protected abstract ObjectReturn a transaction object for the current transaction state.protected ObjectReturn a transaction object for the current transaction state.<R> Rexecute(TransactionDefinition definition, TransactionCallback<T, R> callback) Execute a transaction within the context of the function.<R> RexecuteRead(TransactionCallback<T, R> callback) Execute a read-only transaction within the context of the function.<R> RexecuteWrite(TransactionCallback<T, R> callback) Execute a default transaction within the context of the function.find()Find optional transaction state.protected SynchronousTransactionStateFind or create a new state.protected TgetConnection(SynchronousTransactionState state, Object transaction) The connection for the given transaction object.protected abstract TgetConnection(Object transaction) The connection for the given transaction object.protected SynchronousTransactionStategetState()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 ObjectGet the transaction state key that should be used to store the state.protected final voidinvokeAfterCompletion(List<TransactionSynchronization> synchronizations, TransactionSynchronization.Status completionStatus) Actually invoke theafterCompletionmethods of the given Spring TransactionSynchronization objects.protected booleanisExistingTransaction(SynchronousTransactionState state, Object transaction) Check if the given transaction object indicates an existing transaction (that is, a transaction which has already started).protected booleanisExistingTransaction(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 voidprepareSynchronization(DefaultTransactionStatus<T> status, TransactionDefinition definition) Initialize transaction synchronization as appropriate.protected voidprepareSynchronization(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 voidregisterAfterCompletionWithExistingTransaction(SynchronousTransactionState state, Object transaction, List<TransactionSynchronization> synchronizations) Register the given list of transaction synchronizations with the existing transaction.protected voidregisterAfterCompletionWithExistingTransaction(Object transaction, List<TransactionSynchronization> synchronizations) Register the given list of transaction synchronizations with the existing transaction.protected final voidresume(Object transaction, AbstractSynchronousTransactionManager.SuspendedResourcesHolder resourcesHolder) Resume the given transaction.final voidrollback(TransactionStatus<T> status) This implementation of rollback handles participating in existing transactions.protected final AbstractSynchronousTransactionManager.SuspendedResourcesHolderSuspend the given transaction.protected final voidtriggerBeforeCommit(DefaultTransactionStatus<T> status) TriggerbeforeCommitcallbacks.protected final voidTriggerbeforeCompletioncallbacks.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, useSavepointForNestedTransactionMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods 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:
doDestroyStatein classAbstractSynchronousStateTransactionManager<T>- Parameters:
state- The state
-
execute
public <R> R execute(@NonNull TransactionDefinition definition, @NonNull TransactionCallback<T, R> callback) Description copied from interface:TransactionOperationsExecute a transaction within the context of the function.- Specified by:
executein interfaceTransactionOperations<T>- Type Parameters:
R- The result- Parameters:
definition- The transaction definitioncallback- The call back- Returns:
- The result
-
executeRead
Description copied from interface:TransactionOperationsExecute a read-only transaction within the context of the function.- Specified by:
executeReadin interfaceTransactionOperations<T>- Type Parameters:
R- The result- Parameters:
callback- The call back- Returns:
- The result
-
executeWrite
Description copied from interface:TransactionOperationsExecute a default transaction within the context of the function.- Specified by:
executeWritein 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:SynchronousTransactionManagerReturn 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:
getTransactionin interfaceSynchronousTransactionManager<T>- Parameters:
definition- the TransactionDefinition instance (can benullfor 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:AbstractSynchronousStateTransactionManagerCreate a TransactionStatus instance for the given arguments.- Overrides:
newTransactionStatusin 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:AbstractSynchronousStateTransactionManagerThe connection for the given transaction object.- Specified by:
getConnectionin 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:AbstractSynchronousStateTransactionManagerInitialize transaction synchronization as appropriate.- Overrides:
prepareSynchronizationin 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 thedoSuspendtemplate method.- Parameters:
transaction- the current transaction object (ornullto just suspend active synchronizations, if any)- Returns:
- an object that holds suspended resources
(or
nullif 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 thedoResumetemplate method first, then resuming transaction synchronization.- Parameters:
transaction- the current transaction objectresourcesHolder- the object that holds suspended resources, as returned bysuspend(ornullto 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,doCommitandrollback.- Specified by:
commitin interfaceSynchronousTransactionManager<T>- Parameters:
status- object returned by thegetTransactionmethod- 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 todoRollbackanddoSetRollbackOnly.- Specified by:
rollbackin interfaceSynchronousTransactionManager<T>- Parameters:
status- object returned by thegetTransactionmethod- 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
TriggerbeforeCommitcallbacks.- Parameters:
status- object representing the transaction
-
triggerBeforeCompletion
TriggerbeforeCompletioncallbacks.- Parameters:
status- object representing the transaction
-
doGetTransaction
protected Object doGetTransaction(@NonNull SynchronousTransactionState state) throws TransactionException Description copied from class:AbstractSynchronousStateTransactionManagerReturn 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
getTransactioncall on the transaction manager. Consequently, adoGetTransactionimplementation will usually look for an existing transaction and store corresponding state in the returned transaction object.- Specified by:
doGetTransactionin 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:AbstractSynchronousStateTransactionManagerCheck 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:
isExistingTransactionin 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 theafterCompletionmethods of the given Spring TransactionSynchronization objects.To be called by this abstract manager itself, or by special implementations of the
registerAfterCompletionWithExistingTransactioncallback.- 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
getTransactioncall on the transaction manager. Consequently, adoGetTransactionimplementation 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:AbstractSynchronousStateTransactionManagerRegister 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
afterCompletionmethods 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:
registerAfterCompletionWithExistingTransactionin classAbstractSynchronousStateTransactionManager<T>- Parameters:
state- The transaction statetransaction- transaction object returned bydoGetTransactionsynchronizations- 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
afterCompletionmethods 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 bydoGetTransactionsynchronizations- a List of TransactionSynchronization objects- Throws:
TransactionException- in case of system errors- See Also:
-
doCleanupAfterCompletion
Description copied from class:AbstractSynchronousStateTransactionManagerCleanup resources after transaction completion.Called after
doCommitanddoRollbackexecution, on any outcome. The default implementation does nothing.Should not throw any exceptions but just issue warnings on errors.
- Overrides:
doCleanupAfterCompletionin classAbstractSynchronousStateTransactionManager<T>- Parameters:
state- The statetransaction- transaction object returned bydoGetTransaction
-
doCleanupAfterCompletion
Cleanup resources after transaction completion.Called after
doCommitanddoRollbackexecution, 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
-