7.2. Obtaining EntityManagers

public EntityManager createEntityManager ();
public EntityManager createEntityManager (PersistenceContextType contextType);

The EntityManagerFactory interface includes three methods for obtaining EntityManagers. The two createEntityManager methods above create a new EntityManager each time they are invoked. The first no-args version always creates an EntityManager with a persistence context type of TRANSACTION. The second version allows you to specify the persistence context type. We relate the differences between persistence context types below.

public EntityManager getEntityManager ();

The third way to obtain an EntityManager from an EntityManagerFactory is through the getEntityManager method. This method is meant for use with application server-managed JTA transactions. It returns the EntityManager associated with the current JTA transaction. If there is no EntityManager bound to the JTA transaction already, the method creates a new EntityManager, binds it to the transaction, and returns it. If no JTA transaction is in progress, the method creates a new EntityManager that will get bound to subsequent JTA transactions. EntityManagers returned from getEntityManager always use the TRANSACTION persistence context.