Enterprise Java Development@TOPIC@

Chapter 97. Persistence Unit/Context Injection

97.1. @PersistenceContext Injection
97.2. @PersistenceUnit Injection
97.3. Context and Dependency Injection (CDI)
97.4. Summary
@PersistenceContext

Injected with EntityManager

Transaction Scoped
  • persistence context only sees a single Tx

  • container injects EntityManager with Tx active

Extended Scope
  • persistence context may see multiple Tx

  • only relevant for Stateful EJBs

@PersistenceUnit

Injected with EntityManagerFactory

  • May be used to implement BEAN-managed transactions


  • @PersistenceContext.unitName is the name used within the persistence.xml

  • @PersistenceContext.name would be the ENC name normally defined in ejb-jar.xml


  • BEAN-managed transactions means JTA transaction controlled thru injected UserTransaction

  • Persistence unit (EntityManagerFactory) being injected from a JTA-managed source

    • i.e., the transaction must be managed at JTA level

  • Method programmatically controlling scope of JTA transaction

  • em.joinTransaction() called on EntityManager created outside scope of JTA transaction

Newer technique -- JavaEE's answer to Spring Configuration