title: Specifying EntityManager in Singleton EJB; access from Stateless EJB. OK? Bad?
body: <p>I want to abstract the details of specifying an EntityManager from the majority of the implementation, so I've put the <code>@PersistenceContext(...) EntityManager em;</code> declaration in a <code>@Singleton</code> bean.  That bean has a <code>getEm()</code> method which the rest of the app uses to get the EntityManager (there are actually several EntityManagers, all done this same way). Each <code>@Stateless</code> bean that does  JPA-related ops injects the <code>@Singleton</code> bean, and then calls the <code>getEm()</code> method to get the EntityManager.</p>
  
  <p>There are three primary reasons for this approach: (1) keep the specification of <code>unitName</code> in the <code>@PersistenceContext</code> declaration in one place (i.e., avoiding repeated injections of <code>@PersistenceContext</code> repeating the <code>unitName</code>); (2) keep options open to change acquisition of the EntityManager from being injected to JNDI lookup later on; (3) when using multiple entity managers in a live/standby scenario, allow some logic to dynamically determine the proper one.</p>
  
  <p>Few questions:</p>
  
  <ol>
  <li>Is this approach inherently flawed?  If so, is there a better way to accomplish the 3 objectives listed?</li>
  <li>When acquiring the EntityManager in this way (when injected into the <code>@Singleton</code>), will each <code>@Stateless</code> bean get a "fresh" EntityManager for every transaction (container-managed transactions).  Or do I need to do something specific to prevent the EntityManager the <code>@Stateless</code> bean is [re]using from becoming stale?</li>
  <li>Same as #2 for JNDI lookup in the <code>@Singleton</code>.</li>
  <li>If each transaction isn't getting a "fresh" EntityManager (presumably due to some JPA/JTA interactions), then I suspect this approach isn't thread-safe due to multiple <code>@Stateless</code> acquisition of single EntityManager from <code>@Singleton</code>. Any approaches to address that?</li>
  </ol>