unified interface independent of implementation
specifies standard Java interface between transaction manager and parties involved in a distributed transaction system
Obtain
JNDI lookup: java:comp/UserTransaction
injection of UserTransaction object
Used in EJB (session or message-driven) with CMT, container sets boundaries of transactions.
If EJB uses CMT, it SHOULD NOT USE any transaction management methods that interfere with container's transaction, that includes:
java.sql.Connection: commit, setAutoCommit, rollback
javax.jms.Session - commit, rollback
UserTransaction interface
Transaction attributes
To set, annotate class or method with javax.ejb.TransactionAttribute and set to one of javax.ejb.TransactionAttributeType.
If annotates the class, type is applied to all business methods.
Example: @TransactionAttribute(NOT_SUPPORTED)
Transaction attributes determines in what transaction (new? existing?) a method runs:
Transaction Rollback
if a system exception is thrown, container automatically roll back
invoke EJBContext.setRollbackOnly
application exception does not cause automatic rollback
Synchronizing session bean's instance variables
SessionSynchronization interface allows stateful session bean instances to receive transaction synchronization notifications to synchronize instance variables. Container call interface methods
afterBegin : immediately before invokes business method
beforeCompletion : after finished business method, last opportunity for rollback
afterCompletion : after completion of transaction, with parameter indicating whether transaction committed
When use application-managed (bean managed) transaction for (1) session bean or (2) message-driven bean, first to decide whether to use (1) Java Database Connectivity or (2) JTA transaction
JTA Transaction
controlled by Java EE transaction manager
independent of transaction manager implementation
can span to multiple database from different vendors
limitation: does not support nested transactions
demarcation methods of javax.transaction.UserTransaction interface:
begin
commit
rollback
for stateful session bean: retains transaction even each business method opens / closes connection
Business method and transaction
For stateless session bean: business method must commit or rollback a transaction before returning (bean can be reused)
For stateful session bean with JTA transaction: association of bean instance and transaction is retained across multiple calls; even if each business method opens and closes database connection, the association is retained until transaction completes.
For stateful session bean with JDBC transaction: the JDBC connection retains the association between bean instance and transaction. If connection is closed, association not retained.
Do not use:
EJBContext.getRollbackOnly / setRollbackOnly
http://smokeandice.blogspot.com/2009/12/cdi-and-declarative-transactions.html