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 102.1. Example: EJB with Bean-Managed Transactions
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class BmtCreateEJB {
@PersistenceContext(unitName="ejbtx-warehouse")
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();
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
Figure 102.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