Top Description Methods
jakarta.persistence

public Interface EntityManager

extends AutoCloseable
Imports
java.util.Map, .List, jakarta.persistence.criteria.CriteriaSelect, .CriteriaBuilder, .CriteriaQuery, .CriteriaUpdate, .CriteriaDelete, jakarta.persistence.metamodel.Metamodel

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 and EntityManagerFactory#callInTransaction.

entityManagerFactory.runInTransaction(entityManager -> { // do work in a persistence context ... });
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;
// 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(); }
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).

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
Query, TypedQuery, CriteriaQuery, PersistenceContext, StoredProcedureQuery, EntityManagerFactory

Method Summary

Modifier and TypeMethod and Description
public <
the connection type, usually java.sql.Connection
C
,
the type of result returned by the function
T
>
T

Returns:

the value returned by ConnectionFunction#apply.
callWithConnection
(ConnectionFunction<C, T>
the function
function
)

Call the given function and return its result using the database connection underlying this EntityManager.

public void
clear()

Clear the persistence context, causing all managed entities to become detached.

public void
close()

Redeclares java.lang.AutoCloseable.close.

Close an application-managed entity manager.

public boolean

Returns:

boolean value indicating if entity belongs to the persistence context
contains
(Object
entity instance
entity
)

Determine if the given object is a managed entity instance belonging to the current persistence context.

public <T> EntityGraph<T>

Returns:

entity graph
createEntityGraph
(Class<T>
class of entity graph
rootType
)

Create a new mutable EntityGraph, allowing dynamic definition of an entity graph.

public EntityGraph<?>

Returns:

entity graph
createEntityGraph
(String
name of an entity graph
graphName
)

Obtain a mutable copy of a named EntityGraph, or return null if there is no entity graph with the given name.

public Query

Returns:

the new query instance
createNamedQuery
(String
the name of a query defined in metadata
name
)

Create an instance of Query for executing a named query written in the Jakarta Persistence query language or in native SQL.

public <T> TypedQuery<T>

Returns:

the new query instance
createNamedQuery
(String
the name of a query defined in metadata
name
,
Class<T>
the type of the query result
resultClass
)

Create an instance of TypedQuery for executing a Jakarta Persistence query language named query.

public StoredProcedureQuery

Returns:

the new stored procedure query instance
createNamedStoredProcedureQuery
(String
name assigned to the stored procedure query in metadata
name
)

Create an instance of StoredProcedureQuery for executing a stored procedure in the database.

public Query

Returns:

the new query instance
createNativeQuery
(String
a native SQL query string
sqlString
)

Create an instance of Query for executing a native SQL statement, e.g., for update or delete.

public <T> Query

Returns:

the new query instance
createNativeQuery
(String
a native SQL query string
sqlString
,
Class<T>
the type of the query result
resultClass
)

Create an instance of Query for executing a native SQL query.

public Query

Returns:

the new query instance
createNativeQuery
(String
a native SQL query string
sqlString
,
String
the name of the result set mapping
resultSetMapping
)

Create an instance of Query for executing a native SQL query.

public Query

Returns:

the new query instance
createQuery
(String
a Jakarta Persistence query string
qlString
)

Create an instance of Query for executing a Jakarta Persistence query language statement.

public <T> TypedQuery<T>

Returns:

the new query instance
createQuery
(CriteriaQuery<T>
a criteria query object
criteriaQuery
)

Create an instance of TypedQuery for executing a criteria query.

public <T> TypedQuery<T>

Returns:

the new query instance
createQuery
(CriteriaSelect<T>
a criteria query object
selectQuery
)

Create an instance of TypedQuery for executing a criteria query, which may be a union or intersection of top-level queries.

public Query

Returns:

the new query instance
createQuery
(CriteriaUpdate<?>
a criteria update query object
updateQuery
)

Create an instance of Query for executing a criteria update query.

public Query

Returns:

the new query instance
createQuery
(CriteriaDelete<?>
a criteria delete query object
deleteQuery
)

Create an instance of Query for executing a criteria delete query.

public <T> TypedQuery<T>

Returns:

the new query instance
createQuery
(String
a Jakarta Persistence query string
qlString
,
Class<T>
the type of the query result
resultClass
)

Create an instance of TypedQuery for executing a Jakarta Persistence query language statement.

public <T> TypedQuery<T>

Returns:

the new query instance
createQuery
(TypedQueryReference<T>
a reference to the query defined in metadata
reference
)

Create an instance of TypedQuery for executing a named query written in the Jakarta Persistence query language or in native SQL.

public StoredProcedureQuery

Returns:

the new stored procedure query instance
createStoredProcedureQuery
(String
name of the stored procedure in the database
procedureName
)

Create an instance of StoredProcedureQuery for executing a stored procedure in the database.

public StoredProcedureQuery

Returns:

the new stored procedure query instance
createStoredProcedureQuery
(String
name 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 StoredProcedureQuery for executing a stored procedure in the database.

public StoredProcedureQuery

Returns:

the new stored procedure query instance
createStoredProcedureQuery
(String
name 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 StoredProcedureQuery for executing a stored procedure in the database.

public void
detach(Object
a managed or removed entity instance
entity
)

Evict the given managed or removed entity from the persistence context, causing the entity to become immediately detached.

public <T> T

Returns:

the found entity instance or null if the entity does not exist
find
(Class<T>
entity class
entityClass
,
Object
primary key
primaryKey
)

Find by primary key.

public <T> T

Returns:

the found entity instance or null if the entity does not exist
find
(Class<T>
entity class
entityClass
,
Object
primary key
primaryKey
,
Map<String, Object>
standard and vendor-specific properties and hints
properties
)

Find by primary key, using the specified properties.

public <T> T

Returns:

the found entity instance or null if the entity does not exist
find
(Class<T>
entity 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 exist
find
(Class<T>
entity 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 exist
find
(Class<T>
entity 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 exist
find
(EntityGraph<T>
entity 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 EntityGraph by primary key, using the specified options, and interpreting the EntityGraph as a load graph.

public void
flush()

Synchronize changes held in the persistence context to the underlying database.

public CacheRetrieveMode
getCacheRetrieveMode()

The cache retrieval mode for this persistence context.

public CacheStoreMode
getCacheStoreMode()

The cache storage mode for this persistence context.

public CriteriaBuilder

Returns:

an instance of CriteriaBuilder
getCriteriaBuilder
()

Obtain an instance of CriteriaBuilder which may be used to construct CriteriaQuery objects.

public Object

Returns:

the underlying provider object
getDelegate
()

Return the underlying provider object for the EntityManager, if available.

public EntityGraph<?>

Returns:

named entity graph
getEntityGraph
(String
name of an existing entity graph
graphName
)

Obtain a named EntityGraph.

public <T> List<EntityGraph<? super T>>

Returns:

list of all entity graphs defined for the entity
getEntityGraphs
(Class<T>
entity class
entityClass
)

Return all named EntityGraphs that are defined for the given entity class type.

public EntityManagerFactory
getEntityManagerFactory()

The entity manager factory which created this entity manager.

public FlushModeType

Returns:

the current FlushModeType
getFlushMode
()

Get the flush mode that applies to all objects contained in the persistence context.

public LockModeType

Returns:

the lock mode currently held
getLockMode
(Object
a 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 of Metamodel
getMetamodel
()

Obtain an instance of the Metamodel interface which provides access to metamodel objects describing the managed types belonging to the persistence unit.

public Map<String, Object>

Returns:

a map of properties and hints currently in effect
getProperties
()

The properties and hints and their associated values which are in effect for this entity manager.

public <T> T

Returns:

a reference to the entity instance
getReference
(Class<T>
entity 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 instance
getReference
(T
a 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 instance
getTransaction
()

Return the resource-level EntityTransaction object.

public boolean

Returns:

boolean
isJoinedToTransaction
()

Determine whether the entity manager is joined to the current transaction.

public boolean

Returns:

true until the entity manager has been closed
isOpen
()

Determine 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
lock(Object
a managed entity instance
entity
,
LockModeType
lock mode
lockMode
,
Map<String, Object>
standard and vendor-specific properties and hints
properties
)

Lock an entity instance belonging to the persistence context, obtaining the specified lock mode, using the specified properties.

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 to
merge
(T
a 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 remove(Object).

public void
refresh(Object
a managed entity instance
entity
)

Refresh the state of the given managed entity instance from the database, overwriting unflushed changes made to the entity, if any.

public void
refresh(Object
a managed entity instance
entity
,
Map<String, Object>
standard and vendor-specific properties and hints
properties
)

Refresh the state of the given managed entity instance from the database, using the specified properties, and overwriting unflushed changes made to the entity, if any.

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
remove(Object
a managed, new, or removed entity instance
entity
)

Mark a managed entity instance as removed, resulting in its deletion from the database when the persistence context is synchronized with the database.

public <
the connection type, usually java.sql.Connection
C
>
void
runWithConnection(ConnectionConsumer<C>
the action
action
)

Execute the given action using the database connection underlying this EntityManager.

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

Returns:

an instance of the specified class
unwrap
(Class<T>
the class of the object to be returned. This is usually either the underlying class implementing EntityManager or an interface it implements.
cls
)

Return an object of the specified type to allow access to a provider-specific API.