0

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?

Sai prateek
  • 11,842
  • 9
  • 51
  • 66

1 Answers1

1

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
    }
}
Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • And how do we go about it, If we want one bean to have two entity managers ? – valik Apr 26 '19 at 10:51
  • 1
    @valik It's probably best to start a second question referencing this one rather than commenting on a very old answer. – Brett Kail May 02 '19 at 00:09