| Method from org.springframework.transaction.support.AbstractPlatformTransactionManager Detail: |
public final void commit(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
if (defStatus.isLocalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Transactional code has requested rollback");
}
processRollback(defStatus);
return;
}
if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
}
processRollback(defStatus);
// Throw UnexpectedRollbackException only at outermost transaction boundary
// or if explicitly asked to.
if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
throw new UnexpectedRollbackException(
"Transaction rolled back because it has been marked as rollback-only");
}
return;
}
processCommit(defStatus);
}
This implementation of commit handles participating in existing
transactions and programmatic rollback requests.
Delegates to isRollbackOnly, doCommit
and rollback. |
protected int determineTimeout(TransactionDefinition definition) {
if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
return definition.getTimeout();
}
return this.defaultTimeout;
}
Determine the actual timeout to use for the given definition.
Will fall back to this manager's default timeout if the
transaction definition doesn't specify a non-default value. |
abstract protected void doBegin(Object transaction,
TransactionDefinition definition) throws TransactionException
Begin a new transaction with semantics according to the given transaction
definition. Does not have to care about applying the propagation behavior,
as this has already been handled by this abstract manager.
This method gets called when the transaction manager has decided to actually
start a new transaction. Either there wasn't any transaction before, or the
previous transaction has been suspended.
A special scenario is a nested transaction without savepoint: If
useSavepointForNestedTransaction() returns "false", this method
will be called to start a nested transaction when necessary. In such a context,
there will be an active transaction: The implementation of this method has
to detect this and start an appropriate nested transaction. |
protected void doCleanupAfterCompletion(Object transaction) {
}
Cleanup resources after transaction completion.
Called after doCommit and doRollback execution,
on any outcome. The default implementation does nothing.
Should not throw any exceptions but just issue warnings on errors. |
abstract protected void doCommit(DefaultTransactionStatus status) throws TransactionException
Perform an actual commit of the given transaction.
An implementation does not need to check the "new transaction" flag
or the rollback-only flag; this will already have been handled before.
Usually, a straight commit will be performed on the transaction object
contained in the passed-in status. |
abstract protected Object doGetTransaction() throws TransactionException
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, a doGetTransaction implementation will usually
look for an existing transaction and store corresponding state in the
returned transaction object. |
protected void doResume(Object transaction,
Object suspendedResources) throws TransactionException {
throw new TransactionSuspensionNotSupportedException(
"Transaction manager [" + getClass().getName() + "] does not support transaction suspension");
}
Resume the resources of the current transaction.
Transaction synchronization will be resumed afterwards.
The default implementation throws a TransactionSuspensionNotSupportedException,
assuming that transaction suspension is generally not supported. |
abstract protected void doRollback(DefaultTransactionStatus status) throws TransactionException
Perform an actual rollback of the given transaction.
An implementation does not need to check the "new transaction" flag;
this will already have been handled before. Usually, a straight rollback
will be performed on the transaction object contained in the passed-in status. |
protected void doSetRollbackOnly(DefaultTransactionStatus status) throws TransactionException {
throw new IllegalTransactionStateException(
"Participating in existing transactions is not supported - when 'isExistingTransaction' " +
"returns true, appropriate 'doSetRollbackOnly' behavior must be provided");
}
Set the given transaction rollback-only. Only called on rollback
if the current transaction participates in an existing one.
The default implementation throws an IllegalTransactionStateException,
assuming that participating in existing transactions is generally not
supported. Subclasses are of course encouraged to provide such support. |
protected Object doSuspend(Object transaction) throws TransactionException {
throw new TransactionSuspensionNotSupportedException(
"Transaction manager [" + getClass().getName() + "] does not support transaction suspension");
}
Suspend the resources of the current transaction.
Transaction synchronization will already have been suspended.
The default implementation throws a TransactionSuspensionNotSupportedException,
assuming that transaction suspension is generally not supported. |
public final int getDefaultTimeout() {
return this.defaultTimeout;
}
Return the default timeout that this transaction manager should apply
if there is no timeout specified at the transaction level, in seconds.
Returns TransactionDefinition.TIMEOUT_DEFAULT to indicate
the underlying transaction infrastructure's default timeout. |
public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
Object transaction = doGetTransaction();
// Cache debug flag to avoid repeated checks.
boolean debugEnabled = logger.isDebugEnabled();
if (definition == null) {
// Use defaults if no transaction definition given.
definition = new DefaultTransactionDefinition();
}
if (isExistingTransaction(transaction)) {
// Existing transaction found - > check propagation behavior to find out how to behave.
return handleExistingTransaction(definition, transaction, debugEnabled);
}
// Check definition settings for new transaction.
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
}
// No existing transaction found - > check propagation behavior to find out how to proceed.
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
}
else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
SuspendedResourcesHolder suspendedResources = suspend(null);
if (debugEnabled) {
logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
}
try {
doBegin(transaction, definition);
}
catch (RuntimeException ex) {
resume(null, suspendedResources);
throw ex;
}
catch (Error err) {
resume(null, suspendedResources);
throw err;
}
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
return newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
}
else {
// Create "empty" transaction: no actual transaction, but potentially synchronization.
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
return newTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
}
}
This implementation handles propagation behavior. Delegates to
doGetTransaction, isExistingTransaction
and doBegin. |
public final int getTransactionSynchronization() {
return this.transactionSynchronization;
}
Return if this transaction manager should activate the thread-bound
transaction synchronization support. |
protected final void invokeAfterCompletion(List synchronizations,
int completionStatus) {
TransactionSynchronizationUtils.invokeAfterCompletion(synchronizations, completionStatus);
}
Actually invoke the afterCompletion methods of the
given Spring TransactionSynchronization objects.
To be called by this abstract manager itself, or by special implementations
of the registerAfterCompletionWithExistingTransaction callback. |
protected boolean isExistingTransaction(Object transaction) throws TransactionException {
return false;
}
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. |
public final boolean isFailEarlyOnGlobalRollbackOnly() {
return this.failEarlyOnGlobalRollbackOnly;
}
Return whether to fail early in case of the transaction being globally marked
as rollback-only. |
public final boolean isGlobalRollbackOnParticipationFailure() {
return this.globalRollbackOnParticipationFailure;
}
Return whether to globally mark an existing transaction as rollback-only
after a participating transaction failed. |
public final boolean isNestedTransactionAllowed() {
return this.nestedTransactionAllowed;
}
Return whether nested transactions are allowed. |
public final boolean isRollbackOnCommitFailure() {
return this.rollbackOnCommitFailure;
}
Return whether doRollback should be performed on failure of the
doCommit call. |
public final boolean isValidateExistingTransaction() {
return this.validateExistingTransaction;
}
Return whether existing transactions should be validated before participating
in them. |
protected DefaultTransactionStatus newTransactionStatus(TransactionDefinition definition,
Object transaction,
boolean newTransaction,
boolean newSynchronization,
boolean debug,
Object suspendedResources) {
boolean actualNewSynchronization = newSynchronization &&
!TransactionSynchronizationManager.isSynchronizationActive();
if (actualNewSynchronization) {
TransactionSynchronizationManager.setActualTransactionActive(transaction != null);
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(
(definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) ?
new Integer(definition.getIsolationLevel()) : null);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly());
TransactionSynchronizationManager.setCurrentTransactionName(definition.getName());
TransactionSynchronizationManager.initSynchronization();
}
return new DefaultTransactionStatus(
transaction, newTransaction, actualNewSynchronization,
definition.isReadOnly(), debug, suspendedResources);
}
Create a new TransactionStatus for the given arguments,
initializing transaction synchronization as appropriate. |
protected void prepareForCommit(DefaultTransactionStatus status) {
}
Make preparations for commit, to be performed before the
beforeCommit synchronization callbacks occur.
Note that exceptions will get propagated to the commit caller
and cause a rollback of the transaction. |
protected void registerAfterCompletionWithExistingTransaction(Object transaction,
List synchronizations) throws TransactionException {
logger.debug("Cannot register Spring after-completion synchronization with existing transaction - " +
"processing Spring after-completion callbacks immediately, with outcome status 'unknown'");
invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
}
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. |
protected final void resume(Object transaction,
AbstractPlatformTransactionManager.SuspendedResourcesHolder resourcesHolder) throws TransactionException {
if (resourcesHolder != null) {
Object suspendedResources = resourcesHolder.suspendedResources;
if (suspendedResources != null) {
doResume(transaction, suspendedResources);
}
List suspendedSynchronizations = resourcesHolder.suspendedSynchronizations;
if (suspendedSynchronizations != null) {
TransactionSynchronizationManager.setActualTransactionActive(resourcesHolder.wasActive);
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(resourcesHolder.isolationLevel);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(resourcesHolder.readOnly);
TransactionSynchronizationManager.setCurrentTransactionName(resourcesHolder.name);
doResumeSynchronization(suspendedSynchronizations);
}
}
}
Resume the given transaction. Delegates to the doResume
template method first, then resuming transaction synchronization. |
public final void rollback(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
processRollback(defStatus);
}
This implementation of rollback handles participating in existing
transactions. Delegates to doRollback and
doSetRollbackOnly. |
public final void setDefaultTimeout(int defaultTimeout) {
if (defaultTimeout < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid default timeout", defaultTimeout);
}
this.defaultTimeout = defaultTimeout;
}
Specify the default timeout that this transaction manager should apply
if there is no timeout specified at the transaction level, in seconds.
Default is the underlying transaction infrastructure's default timeout,
e.g. typically 30 seconds in case of a JTA provider, indicated by the
TransactionDefinition.TIMEOUT_DEFAULT value. |
public final void setFailEarlyOnGlobalRollbackOnly(boolean failEarlyOnGlobalRollbackOnly) {
this.failEarlyOnGlobalRollbackOnly = failEarlyOnGlobalRollbackOnly;
}
Set whether to fail early in case of the transaction being globally marked
as rollback-only.
Default is "false", only causing an UnexpectedRollbackException at the
outermost transaction boundary. Switch this flag on to cause an
UnexpectedRollbackException as early as the global rollback-only marker
has been first detected, even from within an inner transaction boundary.
Note that, as of Spring 2.0, the fail-early behavior for global
rollback-only markers has been unified: All transaction managers will by
default only cause UnexpectedRollbackException at the outermost transaction
boundary. This allows, for example, to continue unit tests even after an
operation failed and the transaction will never be completed. All transaction
managers will only fail earlier if this flag has explicitly been set to "true". |
public final void setGlobalRollbackOnParticipationFailure(boolean globalRollbackOnParticipationFailure) {
this.globalRollbackOnParticipationFailure = globalRollbackOnParticipationFailure;
}
Set whether to globally mark an existing transaction as rollback-only
after a participating transaction failed.
Default is "true": If a participating transaction (e.g. with
PROPAGATION_REQUIRES or PROPAGATION_SUPPORTS encountering an existing
transaction) fails, the transaction will be globally marked as rollback-only.
The only possible outcome of such a transaction is a rollback: The
transaction originator cannot make the transaction commit anymore.
Switch this to "false" to let the transaction originator make the rollback
decision. If a participating transaction fails with an exception, the caller
can still decide to continue with a different path within the transaction.
However, note that this will only work as long as all participating resources
are capable of continuing towards a transaction commit even after a data access
failure: This is generally not the case for a Hibernate Session, for example;
neither is it for a sequence of JDBC insert/update/delete operations.
Note:This flag only applies to an explicit rollback attempt for a
subtransaction, typically caused by an exception thrown by a data access operation
(where TransactionInterceptor will trigger a PlatformTransactionManager.rollback()
call according to a rollback rule). If the flag is off, the caller can handle the exception
and decide on a rollback, independent of the rollback rules of the subtransaction.
This flag does, however, not apply to explicit setRollbackOnly
calls on a TransactionStatus, which will always cause an eventual
global rollback (as it might not throw an exception after the rollback-only call).
The recommended solution for handling failure of a subtransaction
is a "nested transaction", where the global transaction can be rolled
back to a savepoint taken at the beginning of the subtransaction.
PROPAGATION_NESTED provides exactly those semantics; however, it will
only work when nested transaction support is available. This is the case
with DataSourceTransactionManager, but not with JtaTransactionManager. |
public final void setNestedTransactionAllowed(boolean nestedTransactionAllowed) {
this.nestedTransactionAllowed = nestedTransactionAllowed;
}
|
public final void setRollbackOnCommitFailure(boolean rollbackOnCommitFailure) {
this.rollbackOnCommitFailure = rollbackOnCommitFailure;
}
Set whether doRollback should be performed on failure of the
doCommit call. Typically not necessary and thus to be avoided,
as it can potentially override the commit exception with a subsequent
rollback exception.
Default is "false". |
public final void setTransactionSynchronization(int transactionSynchronization) {
this.transactionSynchronization = transactionSynchronization;
}
Set when this transaction manager should activate the thread-bound
transaction synchronization support. Default is "always".
Note that transaction synchronization isn't supported for
multiple concurrent transactions by different transaction managers.
Only one transaction manager is allowed to activate it at any time. |
public final void setTransactionSynchronizationName(String constantName) {
setTransactionSynchronization(constants.asNumber(constantName).intValue());
}
Set the transaction synchronization by the name of the corresponding constant
in this class, e.g. "SYNCHRONIZATION_ALWAYS". |
public final void setValidateExistingTransaction(boolean validateExistingTransaction) {
this.validateExistingTransaction = validateExistingTransaction;
}
Set whether existing transactions should be validated before participating
in them.
When participating in an existing transaction (e.g. with
PROPAGATION_REQUIRES or PROPAGATION_SUPPORTS encountering an existing
transaction), this outer transaction's characteristics will apply even
to the inner transaction scope. Validation will detect incompatible
isolation level and read-only settings on the inner transaction definition
and reject participation accordingly through throwing a corresponding exception.
Default is "false", leniently ignoring inner transaction settings,
simply overriding them with the outer transaction's characteristics.
Switch this flag to "true" in order to enforce strict validation. |
protected boolean shouldCommitOnGlobalRollbackOnly() {
return false;
}
Return whether to call doCommit on a transaction that has been
marked as rollback-only in a global fashion.
Does not apply if an application locally sets the transaction to rollback-only
via the TransactionStatus, but only to the transaction itself being marked as
rollback-only by the transaction coordinator.
Default is "false": Local transaction strategies usually don't hold the rollback-only
marker in the transaction itself, therefore they can't handle rollback-only transactions
as part of transaction commit. Hence, AbstractPlatformTransactionManager will trigger
a rollback in that case, throwing an UnexpectedRollbackException afterwards.
Override this to return "true" if the concrete transaction manager expects a
doCommit call even for a rollback-only transaction, allowing for
special handling there. This will, for example, be the case for JTA, where
UserTransaction.commit will check the read-only flag itself and
throw a corresponding RollbackException, which might include the specific reason
(such as a transaction timeout).
If this method returns "true" but the doCommit implementation does not
throw an exception, this transaction manager will throw an UnexpectedRollbackException
itself. This should not be the typical case; it is mainly checked to cover misbehaving
JTA providers that silently roll back even when the rollback has not been requested
by the calling code. |
protected final AbstractPlatformTransactionManager.SuspendedResourcesHolder suspend(Object transaction) throws TransactionException {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
List suspendedSynchronizations = doSuspendSynchronization();
try {
Object suspendedResources = null;
if (transaction != null) {
suspendedResources = doSuspend(transaction);
}
String name = TransactionSynchronizationManager.getCurrentTransactionName();
TransactionSynchronizationManager.setCurrentTransactionName(null);
boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
TransactionSynchronizationManager.setActualTransactionActive(false);
return new SuspendedResourcesHolder(
suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
}
catch (RuntimeException ex) {
// doSuspend failed - original transaction is still active...
doResumeSynchronization(suspendedSynchronizations);
throw ex;
}
catch (Error err) {
// doSuspend failed - original transaction is still active...
doResumeSynchronization(suspendedSynchronizations);
throw err;
}
}
else if (transaction != null) {
// Transaction active but no synchronization active.
Object suspendedResources = doSuspend(transaction);
return new SuspendedResourcesHolder(suspendedResources);
}
else {
// Neither transaction nor synchronization active.
return null;
}
}
Suspend the given transaction. Suspends transaction synchronization first,
then delegates to the doSuspend template method. |
protected final void triggerBeforeCommit(DefaultTransactionStatus status) {
if (status.isNewSynchronization()) {
if (status.isDebug()) {
logger.trace("Triggering beforeCommit synchronization");
}
TransactionSynchronizationUtils.triggerBeforeCommit(status.isReadOnly());
}
}
Trigger beforeCommit callbacks. |
protected final void triggerBeforeCompletion(DefaultTransactionStatus status) {
if (status.isNewSynchronization()) {
if (status.isDebug()) {
logger.trace("Triggering beforeCompletion synchronization");
}
TransactionSynchronizationUtils.triggerBeforeCompletion();
}
}
Trigger beforeCompletion callbacks. |
protected boolean useSavepointForNestedTransaction() {
return true;
}
Return whether to use a savepoint for a nested transaction.
Default is true, which causes delegation to DefaultTransactionStatus
for creating and holding a savepoint. If the transaction object does not implement
the SavepointManager interface, a NestedTransactionNotSupportedException will be
thrown. Else, the SavepointManager will be asked to create a new savepoint to
demarcate the start of the nested transaction.
Subclasses can override this to return false, causing a further
call to doBegin - within the context of an already existing transaction.
The doBegin implementation needs to handle this accordingly in such
a scenario. This is appropriate for JTA, for example. |