title: Jersey, Guice and Hibernate - EntityManager thread safety
body: <p>I have used this tutorial them same way in my application:
  <a href="http://www.benmccann.com/hibernate-with-jpa-annotations-and-guice/" rel="nofollow">http://www.benmccann.com/hibernate-with-jpa-annotations-and-guice/</a></p>
  
  <p>My app is JAX-RS web service which will receive many concurrent requests and make updates to database. </p>
  
  <p>GenericDAOImpl.java implementation:</p>
  
  <pre><code>public class GenericDAOImpl&lt;T&gt; implements GenericDAO&lt;T&gt; {
  
      @Inject
      protected EntityManager entityManager;
  
      private Class&lt;T&gt; type;
  
      public GenericDAOImpl(){}
  
      public GenericDAOImpl(Class&lt;T&gt; type) {
          this.type = type;
      }
  
      @Override
      public void save(T entity) {
          entityManager.getTransaction().begin();
          entityManager.persist(entity);
          entityManager.getTransaction().commit();
      }
  </code></pre>
  
  <p>}</p>
  
  <p>If 2 concurrent threads try to save entity, I get</p>
  
  <pre><code>java.lang.IllegalStateException: Transaction already active
  </code></pre>
  
  <p>Saving works well if I comment transaction.</p>
  
  <p>I have tried to use </p>
  
  <pre><code>@Inject
  protected Provider&lt;EntityManager&gt; entityManagerProvider;
  </code></pre>
  
  <p>or </p>
  
  <pre><code>@Inject
  protected EntityManagerFactory entityManagerProvider;
  </code></pre>
  
  <p>and for each request:</p>
  
  <pre><code>EntityManager entityManager = entityManagerProvider.get()
  </code></pre>
  
  <p>But then I get:</p>
  
  <pre><code>org.hibernate.PersistentObjectException: detached entity passed to persist
  </code></pre>
  
  <p>What is correct way to implement Guice + Hibernate EntityManager injection / thread-safe generic DAO class?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Andrew Rayner comment from
  <a href="http://www.benmccann.com/hibernate-with-jpa-annotations-and-guice/" rel="nofollow">http://www.benmccann.com/hibernate-with-jpa-annotations-and-guice/</a></p>
  
  <p>"The logic isn’t really production ready – at least if used in a web app.</p>
  
  <p>Hibernates connection pool is very basic and is not production ready – the recommendation is to use a datasource pool such as c3p0.</p>
  
  <p>EntityManager shouldn’t be reused – it is intended to be created per transaction/request. There is a good chance of polluting subsequent requests.</p>
  
  <p>There is also no transaction rollback if something goes wrong.</p>
  
  <p>An interesting approach – but it would be much safer for webapps to use Guices own Persist extension module for managing the lifecycle of EntityMananger instances and transactions."</p>