Enterprise Java Development@TOPIC@

Chapter 99. Persistence Unit/Context Injection

99.1. @PersistenceContext Injection
99.2. @PersistenceUnit Injection
99.3. Context and Dependency Injection (CDI)
99.4. Summary
@PersistenceContext

Injected with EntityManager

Transaction Scoped (default)
  • persistence context only sees a single Tx

  • container injects EntityManager with Tx active

@PersistenceContext(unitName="ejbjpa-hotel", type=PersistenceContextType.TRANSACTION)

private EntityManager em;
Extended Scope
  • persistence context may see multiple Tx

  • only relevant for Stateful EJBs

@PersistenceContext(unitName="ejbjpa-hotel", type=PersistenceContextType.EXTENDED)

private EntityManager em;
@PersistenceUnit

Injected with EntityManagerFactory

  • May be used to implement BEAN-managed transactions

@Stateless

public class HotelMgmtEJB implements HotelMgmtRemote, HotelMgmtLocal {
    @PersistenceContext(unitName="ejbjpa-hotel")
    private EntityManager em;
    private HotelDAO dao;
    private HotelMgmt hotelMgmt; 
    
    @PostConstruct
    public void init() {
        dao = new JPAHotelDAO();
        ((JPAHotelDAO)dao).setEntityManager(em);
        
        hotelMgmt = new HotelMgmtImpl();
        ((HotelMgmtImpl)hotelMgmt).setHotelDao(dao);
    }
@Singleton

@Startup
@TransactionManagement(TransactionManagementType.BEAN)
public class HotelInitEJB implements HotelInitRemote {
    @PersistenceUnit(unitName="ejbjpa-hotel")
    private EntityManagerFactory emf;
    
    @Resource
    private UserTransaction tx;
    
    @Override
    public void businessMethod() {
        EntityManager em=emf.createEntityManager();
        HotelDAO dao = new JPAHotelDAO();
        ((JPAHotelDAO)dao).setEntityManager(em);
        tx.begin();        
        em.joinTransaction(); //tells the EM to join the JTA Tx
        ...
        tx.commit();
        em.close();
    }
}

Newer technique -- JavaEE's answer to Spring Configuration