Enterprise Java Development@TOPIC@

Chapter 102. Bean-Managed Transactions

102.1. UserTransaction
102.2. Message-Driven Callbacks and Bean-Managed Transactions
102.3. Summary

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