Class Transaction
- Direct Known Subclasses:
DefaultTransaction
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classprotected static interfaceprotected class -
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidMakes this transaction the new current transaction.voidactivateCache(boolean activate) activated the cache for the current transaction (thread).voidaddDelayedConstraint(Item item, Item.ItemConstraint constr) voidaddToDelayedRemoval(EntityInstance entity) voidaddToDelayedRollbackLocalInvalidations(Object[] key, int type, int topicdepth) protected voidvoidvoidbegin()protected voidprotected ConnectionImplbindConnection(Tenant tenant, boolean userTAEnabled) protected booleanprotected voidprotected voidprotected voidprotected voidvoidclearDelayedConstrains(PK itemPK) protected voidprotected voidclearTxBoundConnectionAndNotify(boolean isCommit) protected voidprotected voidvoidcommit()protected voidprotected static Transactionstatic Transactioncurrent()Returns the current transaction instance.protected voidbooleanvoidenableDelayedStore(boolean delay) the "delayed store" feature enables you to delay all item modifications until the end of the transaction.voidenableTxCache(boolean enable) For a running transaction this method allow to define whether or not a local cache should be used.static voidenableUserTransactionForThread(boolean enable) Enable or disable the user of UserTransactions for the current thread.execute(TransactionBody transactionBody) Executes given code inside the current transaction.<T> Texecute(TransactionBody.GenericTransactionBody<T> transactionBody) Executes given code inside the current transaction.<T> Texecute(TransactionBody.GenericTransactionBody<T> transactionBody, Class<? extends Exception>... permittedExceptions) Executes given code inside the current transaction.execute(TransactionBody transactionBody, Class<? extends Exception>... permittedExceptions) Executes given code inside the current transaction.booleanvoidvoidexecuteOrDelayStore(EntityInstance entity) protected voidfinishExecute(Throwable thrown, TransactionBody body, Class<? extends Exception>... permittedExceptions) voidAll entity modification delayed within the current transaction will be made persistent right now.protected voidflushDelayedStore(EntityInstance entity) protected AfterSaveListenerRegistry<T> TgetAttached(Class<T> classOfAttachedObject) Returns a stack frame for currents transactionbegin().protected ConnectionImplgetConnectionToBind(HybrisDataSource dataSource) protected ConnectionImplgetConnectionToBindWithRetry(HybrisDataSource dataSource) getContextEntry(Object key) protected static Transactionprotected AfterSaveEventChangesCollectorlongreturns a unique id for this Transaction object.intReturns the number of transactions that are open for this thread, which is of course 0 if no transaction is running, 1 if a transaction is running, 2 if we have a nested transaction and so on.protected TransactionAwareCachegetOrCreateGlobalCacheAdapter(Cache globalCache) protected TransactionAwareCachegetOrCreateLegacyCacheAdapter(Cache globalCache) protected TransactionAwareCachegetOrCreateTxLocalCacheAdapter(Cache globalCache) getOrLoadTxBoundEntityInstance(PersistencePool pool, String jndi, PK pk) getTransactionAwareCache(Cache globalCache) protected static Transaction.TransactionFactoryInside a transaction this method returns the transaction bound database connection.protected voidvoidinvalidate(AbstractCacheUnit unit, int invalidationType) voidinvalidate(AbstractCacheUnit unit, int invalidationType, boolean sendImmediately) voidinvalidate(Object[] key, int invalidationTopicDepth, int invalidationType) voidinvalidate(Object[] key, int invalidationTopicDepth, int invalidationType, boolean sendImmediately) voidinvalidateAndNotifyCommit(Object[] key, int invalidationDepth, int invalidationType) voidinvalidateAndNotifyRollback(Object[] key, int invalidationDepth, int invalidationType) voidinvalidateFromDirectPersistence(Object[] key, PK pk, int invalidationType) booleanbooleanreturns true if all entity modifications should be delayed until the end of the TX.protected booleanisExceptionIsPermitted(Throwable thrown, Class<? extends Exception>... permittedExceptions) static booleanChecks whether there is a transaction running in the current thread and this transaction is in commit or rollback phase (including invalidation phase).booleanisInvalidated(Object[] key) booleanisNested()booleanbooleanTells if this transaction has been marked as rollback-only.final booleanTells if there is currently a active transaction.booleanTells whether this (running) transaction is using a local cache for all lookups which cannot be backed by the global 2n level cache due to this transaction having invalidation recorded affecting the lookup.static booleancheck the value set using the enableUserTransactionForThread(Boolean) method.protected voidvoidLock's an entity for update, performing a row-level lock on the database.protected voidprotected voidprotected voidvoidvoidprotected voidprotected voidstatic TransactionperformCommitBeginEvery(Transaction existingTransaction, int ms) Helper method to commit a transaction after it's running over given amount of time.voidvoidregisterEntityInstance(EntityInstance instance) voidprotected voidvoidrollback()protected voidprotected voidprotected voidprotected voidvoidsetContextEntry(Object key, Object value) voidsetRollbackOnCommitError(boolean rollback) If set totrueany error happening during database commit will cause also a rollback on database level.final voidMarks this transaction as rollback only.protected static voidsetTransactionFactory(Transaction.TransactionFactory transactionFactory) voidsetTransactionIsolationLevel(int level) Allows to choose the transaction isolation level to be used for starting a new transaction.static <ET extends Exception>
ETtoException(Throwable e, Class<ET> businessExceptionClass) Utility method to help handling business exceptions coming fromexecute(TransactionBody)method.protected static voidprotected voidfinal booleanuseCache(AbstractCacheUnit cache) protected abstract booleanuseCacheInternal(AbstractCacheUnit cacheUnit) by implementing this method subclasses can influence the result ofuseCache(AbstractCacheUnit)
-
Field Details
-
CFG_ROLLBACK_ON_COMMIT_ERROR
-
CFG_ENABLE_TX_CACHE
- See Also:
-
CFG_CONNECTION_RETRY_ON_BIND_COUNT
- See Also:
-
CFG_EXECUTE_THROWS_EXCEPTION_FOR_BROKEN_CONNECTION
- See Also:
-
captureInvalidationStackTraces
public static boolean captureInvalidationStackTraces -
lastStartTL
-
attachedObjects
-
-
Constructor Details
-
Transaction
public Transaction()
-
-
Method Details
-
setTransactionFactory
-
unsetTransactionFactory
protected static void unsetTransactionFactory() -
getTransactionsFactory
-
getEntityChangesCollector
-
printContextInfo
public void printContextInfo() -
getBeginTransactionStack
Returns a stack frame for currents transactionbegin(). For diagnostic purposes only. -
current
Returns the current transaction instance. Please note that creating nested transactions by callingbegin()does not create new transaction instances. After finishing the (outermost) transaction viacommit()orrollback()the instance is discarded. The next call tocurrent()creates a new instance. -
getCurrentIfExists
-
isCurrent
public boolean isCurrent() -
createNew
-
getObjectID
public long getObjectID()returns a unique id for this Transaction object. Note that this ID stays the same if you call begin(), commit() more than once on the same object- Returns:
- the unique object ID
-
isRunning
public final boolean isRunning()Tells if there is currently a active transaction. Oncebegin()has been called the transaction is considered to be active. After callingcommit()orrollback()the transaction is no longer active. If nested transactions are started it returnstrueuntilcommit()orrollback()has been called on the outermost transaction even if inner transactions have been ended via commit or rollback. -
isNested
public boolean isNested() -
setRollbackOnly
public final void setRollbackOnly()Marks this transaction as rollback only. If this transaction is nested all enclosing transactions are marked rollback-only too. Callingcommit()afterwards will in fact roll back the transaction and throw aTransactionExceptionto indicate that commit has not been successful (only outermost transaction - nested transactions do not throw a exception). Example:Transaction.current().begin(); { Transaction.current().begin(); { Transaction.current().setRollbackOnly(); } Transaction.current().commit(); // no exception here; no commit or rollback either } Transaction.current().commit(); // throws exception + does rollback -
isRollbackOnly
public boolean isRollbackOnly()Tells if this transaction has been marked as rollback-only. This happens by callingsetRollbackOnly()orrollback()upon a nested transaction. SeesetRollbackOnly()for more details. -
clearRollbackOnly
protected void clearRollbackOnly() -
isInCommitOrRollback
public static boolean isInCommitOrRollback()Checks whether there is a transaction running in the current thread and this transaction is in commit or rollback phase (including invalidation phase). This phase includes the commit/rollback call to the database and the followed notification/invalidation. Note: Do not use this method in your business code. This is a hybris internal method.- Returns:
- true in case transaction is in commit or rollback phase
- Since:
- 3.1-u4
-
getOpenTransactionCount
public int getOpenTransactionCount()Returns the number of transactions that are open for this thread, which is of course 0 if no transaction is running, 1 if a transaction is running, 2 if we have a nested transaction and so on.- Returns:
- the number of open transactions for this thread
-
increaseOpenTransactionCount
protected void increaseOpenTransactionCount() -
decreaseOpenTransactionCount
protected void decreaseOpenTransactionCount() -
calculatedUserTAEnabled
-
begin
- Throws:
TransactionException
-
onNestedBeginError
-
onOuterBeginError
-
checkForOtherCurrentTxRunning
protected void checkForOtherCurrentTxRunning() -
beginOuter
protected void beginOuter() -
loadAfterSaveListenerRegistry
protected void loadAfterSaveListenerRegistry() -
getAfterSaveEventListenerRegistry
-
bindConnection
-
logBeforeBegin
protected void logBeforeBegin() -
getConnectionToBindWithRetry
protected ConnectionImpl getConnectionToBindWithRetry(HybrisDataSource dataSource) throws SQLException - Throws:
SQLException
-
getConnectionToBind
- Throws:
SQLException
-
commit
- Throws:
TransactionException
-
commitConnectionAndClearAndUnsetAsCurrent
protected void commitConnectionAndClearAndUnsetAsCurrent() -
checkBeforeCommit
protected void checkBeforeCommit() -
logBeforeCommit
protected void logBeforeCommit() -
toException
Utility method to help handling business exceptions coming fromexecute(TransactionBody)method. -
clearTxBoundConnectionAndNotifyCommit
protected void clearTxBoundConnectionAndNotifyCommit() -
clearTxBoundConnectionAndNotifyRollback
protected void clearTxBoundConnectionAndNotifyRollback() -
clearTxBoundConnectionAndNotify
protected void clearTxBoundConnectionAndNotify(boolean isCommit) -
unsetTxBoundConnection
protected void unsetTxBoundConnection() -
checkDelayedConstrains
- Throws:
ConsistencyCheckException
-
invalidateAndNotifyCommit
-
notifyCommit
public void notifyCommit() -
rollback
- Throws:
TransactionException
-
checkBeforeRollback
protected void checkBeforeRollback() -
logBeforeRollback
protected void logBeforeRollback() -
rollbackOuter
protected void rollbackOuter() -
rollbackConnection
- Throws:
SQLException
-
rollbackConnection
- Throws:
SQLException
-
invalidateAndNotifyRollback
-
notifyRollback
public void notifyRollback() -
execute
Executes given code inside the current transaction. If this transaction is not currently running it will be started and committed at the end of execution. Otherwise whetherbeginnorcommitis called since the enclosing transaction will do that.In case an exception is raised and this method started the transaction itself it will rollback any changes. If no own transaction was started the exception is simply thrown to the calling code.
- Parameters:
transactionBody- the code to execute within this transaction- Returns:
- the object returned by the executed code
- Throws:
Exception- in case the executed code raised an exception
-
execute
Executes given code inside the current transaction. If this transaction is not currently running it will be started and committed at the end of execution. Otherwise whetherbeginnorcommitis called since the enclosing transaction will do that.In case an exception is raised and this method started the transaction itself it will rollback any changes. If no own transaction was started the exception is simply thrown to the calling code.
- Type Parameters:
T- type of the returned object- Parameters:
transactionBody- the code to execute within this transaction- Returns:
- the object returned by the executed code
- Throws:
Exception- in case the executed code raised an exception
-
execute
public <T> T execute(TransactionBody.GenericTransactionBody<T> transactionBody, Class<? extends Exception>... permittedExceptions) throws Exception Executes given code inside the current transaction. If this transaction is not currently running it will be started and committed at the end of execution. Otherwise whetherbeginnorcommitis called since the enclosing transaction will do that.In case an exception is raised and this method started the transaction itself it will rollback any changes. If no own transaction was started the exception is simply thrown to the calling code.
- Type Parameters:
T- type of the returned object- Parameters:
transactionBody- the code to execute within this transactionpermittedExceptions- a list of exception classes which are actually allowed to be thrown without the transaction being rolled back; may be null if no exceptions are allowed to do so- Returns:
- the object returned by the executed code
- Throws:
Exception- in case the executed code raised an exception
-
execute
public Object execute(TransactionBody transactionBody, Class<? extends Exception>... permittedExceptions) throws Exception Executes given code inside the current transaction. If this transaction is not currently running it will be started and committed at the end of execution. Otherwise whetherbeginnorcommitis called since the enclosing transaction will do that.In case an exception is raised and this method started the transaction itself it will rollback any changes. If no own transaction was started the exception is simply thrown to the calling code.
- Parameters:
transactionBody- the code to execute within this transactionpermittedExceptions- a list of exception classes which are actually allowed to be thrown without the transaction being rolled back; may be null if no exceptions are allowed to do so- Returns:
- the object returned by the executed code
- Throws:
Exception- in case the executed code raised an exception
-
finishExecute
protected void finishExecute(Throwable thrown, TransactionBody body, Class<? extends Exception>... permittedExceptions) throws Exception - Throws:
Exception
-
isExceptionIsPermitted
-
getContextEntry
-
setContextEntry
-
invalidate
-
invalidate
-
invalidate
-
invalidateFromDirectPersistence
-
removeFromEntityMap
-
invalidate
public void invalidate(Object[] key, int invalidationTopicDepth, int invalidationType, boolean sendImmediately) -
addToDelayedRollbackLocalInvalidations
-
useCache
-
activateCache
public void activateCache(boolean activate) activated the cache for the current transaction (thread). WARNING: if deactivating the cache be sure you reactivate it inside a finally{} clause to avoid slowdown of the system.- Parameters:
activate- true to activate, false to deactivate- Since:
- 2.0
-
useCacheInternal
by implementing this method subclasses can influence the result ofuseCache(AbstractCacheUnit) -
isInvalidated
- Returns:
- true if the given key will be invalidated by executeInvalidations()
-
enableDelayedStore
public void enableDelayedStore(boolean delay) the "delayed store" feature enables you to delay all item modifications until the end of the transaction. note that if you set this parameter it will be resetted after each commit/rollback to the global parameter "transaction.delayedstore" in your project|local.properties. -
setRollbackOnCommitError
public void setRollbackOnCommitError(boolean rollback) If set totrueany error happening during database commit will cause also a rollback on database level. Normally this is not necessary but should be considered in case database transactions are still open after commit.Also see configuration parameter 'transaction.rollbackOnCommitError' which allows to enable this globally.
-
isRollbackOnCommitError
public boolean isRollbackOnCommitError() -
isDelayedStoreEnabled
public boolean isDelayedStoreEnabled()returns true if all entity modifications should be delayed until the end of the TX. If not used the enableDelayedStore() method, the result will be the preset given in the parameter "transaction.delayedstore" (or true if this has not been specified) -
flushDelayedStore
public void flushDelayedStore()All entity modification delayed within the current transaction will be made persistent right now. Please note that no changes will be written to database in case this transaction is already marked asrollback-only! -
flushDelayedStore
-
executeOrDelayStore
-
addToDelayedRemoval
-
executeOnRollback
-
executeOnCommit
-
enableUserTransactionForThread
public static void enableUserTransactionForThread(boolean enable) Enable or disable the user of UserTransactions for the current thread. If you globally want to enable/disable this feature, use the config parameter transaction.enable=true|false (can be found in the project.properties).- Parameters:
enable- true to enable, false to disable UserTransactions for the current thread- Since:
- 1.3.1
-
isUserTransactionEnabled
public static boolean isUserTransactionEnabled()check the value set using the enableUserTransactionForThread(Boolean) method. Note that there may be more parameters that are checked internally if a UserTransaction should be started, eg. this method may return true, but the global configuration parameter "transaction.enable" is set to false. in this case no transaction is started.- Returns:
- false, if the user transactions are disabled using the 'enableUserTransactionForThread(..)' method, true otherwise.
- Since:
- 1.3.1
-
activateAsCurrentTransaction
public void activateAsCurrentTransaction()Makes this transaction the new current transaction.- Throws:
IllegalStateException- if there is still a current transaction set which is running.- Since:
- 2.10
-
assertNoCurrentTransactionRunning
protected void assertNoCurrentTransactionRunning() -
setAsCurrent
protected void setAsCurrent() -
registerEntityInstance
-
getOrLoadTxBoundEntityInstance
- Parameters:
pool-jndi-pk-- Throws:
YNoSuchEntityException- is there is no item for the given pk
-
getAttachedEntityInstance
-
reloadEntityInstance
-
getTXBoundConnection
Inside a transaction this method returns the transaction bound database connection.- Throws:
IllegalStateException- if called outside a transaction
-
setTransactionIsolationLevel
public void setTransactionIsolationLevel(int level) Allows to choose the transaction isolation level to be used for starting a new transaction. Please set before starting. Otherwise behavior is not defined (seeConnection.setTransactionIsolation(int)for details)!Use as follows:
Transaction tx = Transaction.current(); tx.setTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED); tx.begin(); // ... business code tx.commit();
Also note that after commit or rolling back the isolation level setting is cleared - it has to be set for each transaction anew!
- Parameters:
level- the level - seeConnectionfor details
-
performCommitBeginEvery
Helper method to commit a transaction after it's running over given amount of time.This method performs a commit on existing transaction and starts new one when elapsed transaction time exceeds given threshold. When new transaction is started, it is returned so that the caller can use it to do further transaction processing (e.g. commit()).
- Parameters:
existingTransaction- existing transactionms- transaction time threshold- Returns:
- New transaction object if the elapsed transaction time is greater than the threshold. Existing transaction otherwise.
-
clearDelayedConstrains
-
addDelayedConstraint
-
lock
Lock's an entity for update, performing a row-level lock on the database.Calls to
lockcan only be made between calls tobegin()andcommit()orrollback(). All locks that are acquired during a transaction are automatically released on calls tocommit()orrollback(). If a lock is held by another transaction, this method will block until the lock can be acquired.Depending on a the DBMS, a lock on a single row may result in locking an entire page. Locks should not be acquired on long-running transactions unless absolutely necessary. Note, that on some DBMS's, such as HSQLDB, row-level locking is not supported and any attempt to perform a lock will throw an UnsupportedOperationException.
Also note that it's crucial to use the correct
isolation levelfor getting the correct result after locking a item. For instance if you expect that a attribute ma have been changed while waiting for that lock it may be a good idea to useConnection.TRANSACTION_READ_COMMITTEDto allow reading these changed values!- Parameters:
item- The entity to lock- Throws:
NullPointerException- If an null value is passed into thelockmethod or if no primary key has been assigned to the entity.IllegalStateException- If an attempt is made to lock an entity outside the bounds of the transaction, or an attempt is made to lock an entity that does not exist in the database.UnsupportedOperationException- If the database does not support SELECT FOR UPDATE
-
getTransactionAwareCache
-
getOrCreateGlobalCacheAdapter
-
getOrCreateTxLocalCacheAdapter
-
getOrCreateLegacyCacheAdapter
-
isTxCacheEnabled
public boolean isTxCacheEnabled()Tells whether this (running) transaction is using a local cache for all lookups which cannot be backed by the global 2n level cache due to this transaction having invalidation recorded affecting the lookup.The default mode is
trueand has the config settingCFG_ENABLE_TX_CACHE.- See Also:
-
enableTxCache
public void enableTxCache(boolean enable) For a running transaction this method allow to define whether or not a local cache should be used.- See Also:
-
attach
-
dettach
-
getAttached
-