title: Entity Manager per Thread design - how to implement
body: <p>I want to know how to implement a JPA EntityManager per user thread design. Since EM are light weight objects, it should not be an overhead to create them per user thread. The problem I want to solve is a single JSP page with multiple (parallel) JSON/AJAX calls to back-end services (via controllers). </p>
  
  <p>I am having an Entity Manager (with persistence context EXTENDED), with Open EM In View Filter. It does work nice, but only when there is one user thread (say, a json call) per page, or in other words when I access em in serial fashion. 
  It does not however solve my purpose when I call my services from multiple threads as em instances are shared and I get weird errors (sometimes shared access to collections, and sometimes closed connection, which are expected I believe).</p>
  
  <p>I am using JPA over Spring 3 and hibernate 3.5. I inject an entity manager (extended) into my services as below: </p>
  
  <pre><code>@PersistenceContext(type = PersistenceContextType.EXTENDED)
  protected EntityManager em;
  </code></pre>
  
  <p>My readonly service methods are annotated as</p>
  
  <pre><code>&lt;tx:method name="get*" read-only="true" propagation="SUPPORTS"/&gt;
  </code></pre>
  
  <p>All other methods, are annotated as</p>
  
  <pre><code>&lt;tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/&gt;
  </code></pre>
  
  <p>I want to avoid an application managed em, and hence did not go for injecting a EntityManagerFactory instead.
  Also, If I choose to inject EntityManager into spring controller, I will still have issues when same controller is called in parallel from two threads !</p>
  
  <p>Is there an elegant way to achieve a thread safe access to em. I also want to avoid locking any entity objects, which complicates things further.</p>
  
  <p>Since multiple ajax calls from same page is a very common design in modern web - applications, I believe there must be a simple and declarative way of achieving this (without going back to managing hibernate sessions manually with interceptors etc)</p>