title: Different ways of getting the EntityManager
body: <p>The usual idiom I see for creating the EntityManager is something like this:</p>
  
  <pre><code>public class BaseDao {
      private static final String PERSISTENCE_UNIT_NAME = "Employee";
  
      EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
  
      public EntityManager getEntityManager() {
        return factory.createEntityManager();
      } 
  }
  </code></pre>
  
  <p><strong>Then it is used like this:</strong></p>
  
  <pre><code>Employee emp = new Employee();
  emp.setName("Joe M");
  getEntityManager().persist(emp);
  </code></pre>
  
  <p><strong>Question is why not do it this way:</strong></p>
  
  <pre><code>public class BaseDao{
      private static final String PERSISTENCE_UNIT_NAME = "Employee";
      EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
      private EntityManager entityManager = null;
  
  
  public void setEntityManger() {
      EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
      this.entityManager = factory.createEntityManager();
  
      }
  
      public EntityManager getEntityManager() {
          return this.entityManager;
      }
  }
  </code></pre>
  
  <p>In other words is there a need to always get the entity manager through <code>factory.createEntityManager()</code>? or can it be created as an instance (or even static) variable and retrieved like that?</p>
  
  <p>To clarify, I am talking about an environment that doesn't use EJB or Spring containers.</p>
  
  <p>Thanks.</p>