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 and
EntityManagerFactory#callInTransaction.
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:
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 and remove 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, 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).
FlushModeType#COMMIT, the persistence context
is flushed before the transaction commits.
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.
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:
Query, TypedQuery, CriteriaQuery, PersistenceContext, StoredProcedureQuery, EntityManagerFactory
| Modifier and Type | Method and Description |
|---|---|
| public < the connection type, usually C, java.sql.Connectionthe type of result returned by the function T> T | Returns: the value returned byConnectionFunction#apply.the function function)Call the given function and return its result using the database connection
underlying this |
| public void | |
| public void | |
| public boolean | |
| public <T> EntityGraph | Returns: entity graphclass of entity graph rootType)Create a new mutable |
| public EntityGraph | Returns: entity graphname of an entity graph graphName)Obtain a mutable copy of a named |
| public Query | Returns: the new query instancethe name of a query defined in metadata name)Create an instance of |
| public <T> TypedQuery | Returns: the new query instancethe name of a query defined in metadata name, Class<T> the type of the query result resultClass)Create an instance of |
| public StoredProcedureQuery | Returns: the new stored procedure query instancename assigned to the stored procedure query in
metadata name)Create an instance of |
| public Query | Returns: the new query instancea native SQL query string sqlString)Create an instance of |
| public <T> Query | Returns: the new query instancea native SQL query string sqlString, Class<T> the type of the query result resultClass)Create an instance of |
| public Query | Returns: the new query instancea native SQL query string sqlString, String the name of the result set mapping resultSetMapping)Create an instance of |
| public Query | Returns: the new query instancea Jakarta Persistence query string qlString)Create an instance of |
| public <T> TypedQuery | Returns: the new query instancea criteria query object criteriaQuery)Create an instance of |
| public <T> TypedQuery | Returns: the new query instancea criteria query object selectQuery)Create an instance of |
| public Query | Returns: the new query instancea criteria update query object updateQuery)Create an instance of |
| public Query | Returns: the new query instancea criteria delete query object deleteQuery)Create an instance of |
| public <T> TypedQuery | Returns: the new query instancea Jakarta Persistence query string qlString, Class<T> the type of the query result resultClass)Create an instance of |
| public <T> TypedQuery | Returns: the new query instancea reference to the query defined in metadata reference)Create an instance of |
| public StoredProcedureQuery | Returns: the new stored procedure query instancename of the stored procedure in the database procedureName)Create an instance of |
| public StoredProcedureQuery | Returns: the new stored procedure query instancename of the stored procedure in the database procedureName, Class<?>... classes to which the result sets
produced by the stored procedure are to be mapped resultClasses)Create an instance of |
| public StoredProcedureQuery | Returns: the new stored procedure query instancename of the stored procedure in the
database procedureName, String... the names of the result set mappings
to be used in mapping result sets
returned by the stored procedure resultSetMappings)Create an instance of |
| public void | |
| public <T> T | |
| public <T> T | |
| public <T> T | Returns: the found entity instance or null if the entity does not existentity class entityClass, Object primary key primaryKey, LockModeType lock mode lockMode)Find by primary key and obtain the given lock type for the resulting entity. |
| public <T> T | Returns: the found entity instance or null if the entity does not existentity class entityClass, Object primary key primaryKey, LockModeType lock mode lockMode, Map<String, Object> standard and vendor-specific properties
and hints properties)Find by primary key and lock the entity, using the specified properties. |
| public <T> T | Returns: the found entity instance or null if the entity does not existentity class entityClass, Object primary key primaryKey, FindOption... standard and vendor-specific options options)Find an instance of the given entity class by primary key, using the specified options. |
| public <T> T | Returns: the found entity instance or null if the entity does not existentity graph interpreted as a load graph entityGraph, Object primary key primaryKey, FindOption... standard and vendor-specific options options)Find an instance of the root entity of the given |
| public void | |
| public CacheRetrieveMode | |
| public CacheStoreMode | |
| public CriteriaBuilder | Returns: an instance ofCriteriaBuilderObtain an instance of |
| public Object | Returns: the underlying provider objectReturn the underlying provider object for the
|
| public EntityGraph | Returns: named entity graphname of an existing entity graph graphName)Obtain a named |
| public <T> List | Returns: list of all entity graphs defined for the entityentity class entityClass)Return all named |
| public EntityManagerFactory | Returns: theEntityManagerFactoryThe entity manager factory which created this entity manager. |
| public FlushModeType | Returns: the currentFlushModeTypeGet the flush mode that applies to all objects contained in the persistence context. |
| public LockModeType | Returns: the lock mode currently helda managed entity instance entity)Get the current lock mode held by this persistence context on the given managed entity instance. |
| public Metamodel | Returns: an instance ofMetamodelObtain an instance of the |
| public Map | Returns: a map of properties and hints currently in effectThe properties and hints and their associated values which are in effect for this entity manager. |
| public <T> T | Returns: a reference to the entity instanceentity class entityClass, Object primary key primaryKey)Obtain a reference to an instance of the given entity class with the given primary key, whose state may be lazily fetched. |
| public <T> T | Returns: a reference to the entity instancea persistent or detached entity instance entity)Obtain a reference to an instance of the entity class of the given object, with the same primary key as the given object, whose state may be lazily fetched. |
| public EntityTransaction | Returns: EntityTransaction instanceReturn the resource-level |
| public boolean | Returns: booleanDetermine whether the entity manager is joined to the current transaction. |
| public boolean | Returns: true until the entity manager has been closedDetermine whether the entity manager is open. |
| public void | joinTransaction()
Indicate to the entity manager that a JTA transaction is active and join the persistence context to it. |
| public void | lock(Object
a managed entity instance entity, LockModeType lock mode lockMode)Lock an entity instance belonging to the persistence context, obtaining the specified lock mode. |
| public void | |
| public void | lock(Object
a managed entity instance entity, LockModeType lock mode lockMode, LockOption... standard and vendor-specific options options)Lock an entity instance belonging to the persistence context, obtaining the specified lock mode, using the specified options. |
| public <T> T | Returns: the managed instance that the state was merged toa new, managed, or detached entity instance entity)Merge the state of the given new or detached entity instance into the current persistence context, resulting in, respectively, an insert or possible update when the persistence context is synchronized with the database. |
| public void | persist(Object
a new, managed, or removed entity instance entity)Make a new entity instance managed and persistent, resulting in
its insertion in the database when the persistence context is
synchronized with the database, or make a removed entity managed,
undoing the effect of a previous call to |
| public void | |
| public void | |
| public void | refresh(Object
a managed entity instance entity, LockModeType lock mode lockMode)Refresh the state of the given managed entity instance from the database, overwriting unflushed changes made to the entity, if any, and obtain the given lock mode. |
| public void | refresh(Object
a managed entity instance entity, LockModeType lock mode lockMode, Map<String, Object> standard and vendor-specific properties
and hints properties)Refresh the state of the given managed entity instance from the database, overwriting unflushed changes made to the entity, if any, and obtain the given lock mode, using the specified properties. |
| public void | refresh(Object
a managed entity instance entity, RefreshOption... standard and vendor-specific options options)Refresh the state of the given managed entity instance from the database, using the specified options, overwriting changes made to the entity, if any. |
| public void | |
| public < the connection type, usually C> voidjava.sql.Connection | runWithConnection(ConnectionConsumer<C>
the action action)Execute the given action using the database connection underlying this
|
| public void | setCacheRetrieveMode(CacheRetrieveMode
cache retrieval mode cacheRetrieveMode)Set the default cache retrieval mode for this persistence context. |
| public void | setCacheStoreMode(CacheStoreMode
cache storage mode cacheStoreMode)Set the default cache storage mode for this persistence context. |
| public void | setFlushMode(FlushModeType
flush mode flushMode)Set the flush mode that applies to all objects contained in the persistence context. |
| public void | setProperty(String
name of the property or hint propertyName, Object value for the property or hint value)Set an entity manager property or hint. |
| public <T> T |