title: JPA 2 - Using the EntityManager in JavaSE - a couple of questions
body: <p>I have a couple questions regarding using the entity manager in a JavaSE environment.</p>
  
  <p>I'm using the repository pattern to perform my CRUD operations on the database. There will be a base repository class like so:</p>
  
  <pre><code>public class Repository&lt;T&gt; implements IRepository&lt;T&gt; {
  
      private EntityManager em;
      private String persistenceUnitName;
  
      public Repository(String persistenceUnitName) {
          this.persistenceUnitName = persistenceUnitName;
      }
  
      @Override
      public T find(Class&lt;T&gt; type, Object id) {
          return em.find(type, id);
      }
  
      private EntityManager getEntityManager() {
          if (this.em == null) {
              EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
  
              em = emf.createEntityManager();
          }
  
          return em;
      }
      ...
      ...
  }
  </code></pre>
  
  <p>I will then have classes like EmployeeRepository that will inherit Repository. These repository classes will be created in my service layer.</p>
  
  <p>Is this a good way of initializing the entity manager? I'm starting to think that it's not - it seems like you should only have one entity manager per persistence unit? Where as in this case you would have an entity manager for every repository you create... How would you go about ensuring you only have one entity manager per persistence unit? Also, I noticed that the entity manager and entity manager factory methods have a close method - when should these be called? On a server terminate event?</p>
  
  <p>If you know of any good sources about using JPA in JavaSE I would appreciate the info.</p>
  
  <p>Thanks!</p>