title: EntityManager Lifecycle when using Oracle's Virtual Private Database
body: <p>I had a few questions all related to the way an entity manager is created and used in an application with respect to <code>Virtual Private Databases</code>, which is a feature in Oracle DB which enables Row Level Security.</p>
  
  <ol>
  <li><p>In a session bean, we generally have the entity manager as a member, and its generally injected by the container. How is this entity manager managed by the container - I mean, if we want to implement a <code>Virtual Private Database</code> then we have to make sure that the <code>Virtual Private Database</code>-context remains valid for the entire user session, and we do not have to set this context everytime before we fire a query. (to include more verbiage here : a session bean implements a couple of functions and each of these functions uses the same entity manager; now, it should not be the case that we set the Virtual Private Database everytime in each of these functions which do some DB manipulations).</p></li>
  <li><p>Further to #1, since the entity manager is cached in the session bean, do we need to explicitly close the entity manager in any scenario? (like we do for JDBC connections?)</p></li>
  <li><p>Also, I was wondering what should be the use case(or design criteria) for using a JTA or a non-JTA datasource. Is the way we create an entity manager dependant on this?</p></li>
  </ol>
  
  <p>To add w.r.t the requirement on VPD: 
  It would be nice if the container managed EM can somehow be made to enforce the VPD per user. Note that EM is injected in here, so there should be a mechanism to set the VPD on the connection(and later retrieve the same connection for 'this' user in 'this' session). </p>
  
  <p>Without an injected EM, i think using a reference to EMF and then setting the properties for the EM can be done. Something like :
  ((org.eclipse.persistence.internal.jpa.EntityManagerImpl)em.getDelegate()).setProperties</p>
  
  <p>It would be an overkill, if the VPD is set everytime before the query is fired, rather the connection should 'maintain' the VPD context during the user's session and later release the connection (after clearing the VPD) back to the pool.</p>