Interface EntityManagerFactory

All Superinterfaces:
AutoCloseable

public interface EntityManagerFactory extends AutoCloseable
Interface used to interact with the persistence unit, and to create new instances of EntityManager.

A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database. If two entity types participate in an association, then they must belong to the same persistence unit.

A persistence unit may be defined by a persistence.xml file, or it may be defined at runtime via the PersistenceConfiguration API.

Every persistence unit has a transaction type, either JTA, or RESOURCE_LOCAL. Resource-local transactions are managed programmatically via the EntityTransaction interface.

An EntityManagerFactory with a lifecycle managed by the application may be created using the static operations of the Persistence class:

Usually, there is exactly one EntityManagerFactory for each persistence unit:

// create a factory at initialization time
static final EntityManagerFactory entityManagerFactory =
        Persistence.createEntityManagerFactory("orderMgt");

Alternatively, in the Jakarta EE environment, a container-managed EntityManagerFactory may be obtained by dependency injection, using PersistenceUnit.

// inject the container-managed factory
@PersistenceUnit(unitName="orderMgt")
EntityManagerFactory entityManagerFactory;

An application-managed EntityManager may be created via a call to createEntityManager(). However, this approach places complete responsibility for cleanup and exception management on the client, and is thus considered error-prone. It is much safer to use the methods runInTransaction(java.util.function.Consumer<jakarta.persistence.EntityManager>) and callInTransaction(java.util.function.Function<jakarta.persistence.EntityManager, R>) to obtain EntityManagers. Alternatively, in the Jakarta EE environment, a container-managed EntityManager may be obtained by dependency injection, using PersistenceContext, and the application need not interact with the EntityManagerFactory directly.

The EntityManagerFactory provides access to certain other useful APIs:

When the application has finished using the entity manager factory, or when the application terminates, the application should close() the entity manager factory. If necessary, a Cleaner may be used:

// factory should be destroyed before program terminates
Cleaner.create().register(entityManagerFactory, entityManagerFactory::close);
Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state.
Since:
1.0
See Also: