Enterprise Java Development@TOPIC@
Programmatic interface to transactions
Interactions through javax.transaction.UserTransaction
interface
Everything between utx.begin() and utx.commit() is within a single transaction
Bean is in control
Figure 104.1. Example: EJB with Bean-Managed Transactions
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class BmtCreateEJB {
//synchronization=SynchronizationType.SYNCHRONIZED is the default
@PersistenceContext(unitName="ejbtx-warehouse",
synchronization=SynchronizationType.SYNCHRONIZED)
private EntityManager em;
@Resource
private UserTransaction utx;
public Product createProduct(Product product) {
try {
txWatcher.watchTransaction(getClass(), super.hashCode());
utx.begin(); //<=== manually start Tx
em.joinTransaction(); //<=== only necessary with UNSYNCHRONIZED
em.persist(product);
utx.commit(); //<=== manually end Tx
logger.debug("createProduct()={}", product);
return product;
} catch (Exception ex) {
try { utx.rollback(); }
catch (Exception ex2) { ... }
throw new EJBException("error managing transaction", ex);
}
}
Can inject @PersistenceContext/EntityManager or @PersistenceUnit/EntityManagerFactory
EntityManager already SYNCHRONIZED with UserTransaction by default
EntityManager can be manually synchronized using em.joinTransaction()
Useful in Stateful Session EJBs were may interact with EntityManager over multiple methods
Figure 104.2. UserTransaction
public interface javax.transaction.UserTransaction {
void begin() throws javax.transaction.NotSupportedException,
javax.transaction.SystemException;
void commit() throws javax.transaction.RollbackException,
javax.transaction.HeuristicMixedException,
javax.transaction.HeuristicRollbackException,
java.lang.SecurityException,
java.lang.IllegalStateException,
javax.transaction.SystemException;
void rollback() throws java.lang.IllegalStateException,
java.lang.SecurityException,
javax.transaction.SystemException;
void setRollbackOnly() throws java.lang.IllegalStateException,
javax.transaction.SystemException;
int getStatus() throws javax.transaction.SystemException;
void setTransactionTimeout(int) throws javax.transaction.SystemException;
}
Current message being processed cannot be made to join current UserTransaction
Must use Container-Managed REQUIRED scope