Enterprise Java Development@TOPIC@

Chapter 104. Bean-Managed Transactions

104.1. UserTransaction
104.2. Message-Driven Callbacks and Bean-Managed Transactions
104.3. Summary

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