Search code examples
entitypersistencejpa-2.0ejb-3.0entitymanager

How can a persistenceContext link with multiple EntityManager


Recently I have gone through PRO JPA2 book and find that "A single persistence context can be link with multiple EntityManager instance."

I have searched for the same but could not found satisfactory answer. Can anybody elaborate this with example?


Solution

  • It's difficult to know exactly what was meant without more context from the book. That said, if you're using container-managed JPA within a global transaction, then each injected EntityManager referring to the same persistence unit will be backed by the same persistence context. For example:

    @Stateless
    public class Bean {
        @PersistenceContext
        EntityManager em1;
    
        @EJB
        OtherBean otherBean;
    
        @TransactionAttribute(REQUIRED) // The type, but for illustration
        public void doWork() {
            // ... use em1
            otherBean.doMoreWork();
        }
    }
    
    @Stateless
    public class OtherBean {
        @PersistenceContext
        EntityManager em2;
    
        public void doMoreWork() {
            // ... use em2, it shares a persistence context with em1
        }
    }