Interface EntityManager

All Superinterfaces:
AutoCloseable

public interface EntityManager extends AutoCloseable
Interface used to interact with the persistence context.

An instance of EntityManager must be obtained from an EntityManagerFactory, and is only able to manage persistence of entities belonging to the associated persistence unit.

An application-managed EntityManager may be created via a call to EntityManagerFactory.createEntityManager(). The EntityManager must be explicitly closed via a call to close(), to allow resources to be cleaned up by the persistence provider. This approach places almost complete responsibility for cleanup and exception management on the client, and is thus considered quite error-prone. It is much safer to use the methods EntityManagerFactory.runInTransaction(java.util.function.Consumer<jakarta.persistence.EntityManager>) and EntityManagerFactory.callInTransaction(java.util.function.Function<jakarta.persistence.EntityManager, R>).

entityManagerFactory.runInTransaction(entityManager -> {
    // do work in a persistence context
    ...
});

In the Jakarta EE environment, a container-managed EntityManager may be obtained by dependency injection, using PersistenceContext.

// inject the container-managed entity manager
@PersistenceContext(unitName="orderMgt")
EntityManager entityManager;

If the persistence unit has resource local transaction management, transactions must be managed using the EntityTransaction obtained by calling getTransaction().

A complete idiom for custom application management of the EntityManager and its associated resource-local EntityTransaction is as follows:

EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
try {
    transaction.begin();
    // do work
    ...
    transaction.commit();
}
catch (Exception e) {
    if (transaction.isActive()) transaction.rollback();
    throw e;
}
finally {
    entityManager.close();
}

Each EntityManager instance is associated with a distinct persistence context. A persistence context is a set of entity instances in which for any given persistent entity identity (defined by an entity type and primary key) there is at most one entity instance. The entity instances associated with a persistence context are considered managed objects, with a well-defined lifecycle under the control of the persistence provider.

Any entity instance can be characterized as being in one of the following lifecycle states:

  • A new entity has no persistent identity, and is not yet associated with any persistence context.
  • A managed entity is an instance with a persistent identity that is currently associated with a persistence context.
  • A detached entity is an instance with a persistent identity that is not (or no longer) associated with any active persistence context.
  • A removed entity is an instance with a persistent identity, and associated with a persistence context, that is scheduled for removal from the database upon transaction commit.

The EntityManager API is used to perform operations that affect the state of the persistence context, or that modify the lifecycle state of individual entity instances. The client may persist(java.lang.Object) and remove(java.lang.Object) instances, find entities by their primary key, and execute queries which range over entity types. An entity may be disassociated from the persistence context by calling detach(java.lang.Object), and a persistence context may be completely cleared, detaching all its entities, by calling clear().

The client may also make changes to the state of an entity instance by mutating the entity directly, or it may request that the state of a detached instance be merged, replacing the state of a managed instance with the same persistent identity. Note that there is no explicit "update" operation; since an entity is a managed object, modifications to its persistent fields and properties are automatically detected, as long as it is associated with an active persistence context.

Modifications to the state of entities associated with a persistence context are not immediately synchronized with the database. Synchronization happens during a process called flush. The timing of the flush process depends on the flush mode, which may be set explicitly by calling setFlushMode(FlushModeType).

  • For FlushModeType.COMMIT, the persistence context is flushed before the transaction commits.
  • For FlushModeType.AUTO, which is the default, the persistence context must also be flushed before execution of any query whose result set would be affected by unflushed modifications to entities associated with the persistence context.
The client may force an immediate flush to occur by calling flush().

At any given moment, a persistence context might hold an optimistic or pessimistic lock on an entity instance. The full range of possible lock types is enumerated by LockModeType. Some operations of this interface, including the methods lock(Object, LockModeType), refresh(Object, LockModeType), and find(Class, Object, LockModeType), accept an explicit LockModeType, allowing the client to request a specific type of lock.

Interaction of the persistence context (or first-level cache) with the second-level cache, if any, may be controlled by calling setCacheRetrieveMode(CacheRetrieveMode) and setCacheStoreMode(CacheStoreMode).

Some operations accept one or more built-in and vendor-specific options:

Since:
1.0
See Also: