package ch.romix.restful.sales;

import java.io.Closeable;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.glassfish.hk2.api.Factory;
import org.glassfish.jersey.server.CloseableService;

public class SalesEntityManagerFactory implements Factory<EntityManager> {
  static final ThreadLocal<EntityManager> ENTITY_MANAGERS = new ThreadLocal<>();

  private final CloseableService closeableService;
  EntityManagerFactory emf;

  @Inject
  public SalesEntityManagerFactory(CloseableService closeableService) {
    this.closeableService = closeableService;
    emf = Persistence.createEntityManagerFactory("sales");
  }

  @Override
  public void dispose(EntityManager em) {
    em.close();
    ENTITY_MANAGERS.remove();
  }

  @Override
  public EntityManager provide() {
    final EntityManager em = emf.createEntityManager();
    ENTITY_MANAGERS.set(em);
    closeableService.add(new Closeable() {
      @Override
      public final void close() {
        em.close();
        ENTITY_MANAGERS.remove();
      }
    });
    return em;
  }
}

@@ -241,24 +241,84 @@
 pi.Factory;%0A
+import org.glassfish.jersey.process.internal.RequestScoped;%0A
 import org.g
@@ -358,16 +358,16 @@
 ervice;%0A
-
 %0Apublic 
@@ -514,16 +514,115 @@
 cal%3C%3E();
+%0A  private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory(%22sales%22);
 %0A%0A  priv
@@ -669,36 +669,8 @@
 ice;
-%0A  EntityManagerFactory emf;
 %0A%0A  
@@ -799,67 +799,8 @@
 ce;%0A
-    emf = Persistence.createEntityManagerFactory(%22sales%22);%0A
   %7D%0A
@@ -909,32 +909,49 @@
  %7D%0A%0A  @Override%0A
+  @RequestScoped%0A
   public EntityM
@@ -965,24 +965,178 @@
 provide() %7B%0A
+    if (ENTITY_MANAGERS.get() == null) %7B%0A      createEntityManager();%0A    %7D%0A    return ENTITY_MANAGERS.get();%0A  %7D%0A%0A  private void createEntityManager() %7B%0A
     final En
@@ -1367,16 +1367,16 @@
   %7D%0A
+
     %7D);%0A
     
@@ -1375,23 +1375,8 @@
 %7D);%0A
-    return em;%0A
   %7D%0A

fix entity manager factory