Interface EntityManager
An EntityManager
instance is associated with
a persistence context. A persistence context is a set of entity
instances in which for any persistent entity identity there is
a unique entity instance. Within the persistence context, the
entity instances and their lifecycle are managed.
The EntityManager
API is used
to create and remove persistent entity instances, to find entities
by their primary key, and to query over entities.
The set of entities that can be managed by a given
EntityManager
instance is defined by a persistence
unit. 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.
- Since:
- Java Persistence 1.0
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionvoid
clear()
Clear the persistence context, causing all managed entities to become detached.void
close()
Close an application-managed entity manager.boolean
Check if the instance is a managed entity instance belonging to the current persistence context.createNamedQuery
(String name) Create an instance ofQuery
for executing a named query (in the Java Persistence query language or in native SQL).<T> TypedQuery
<T> createNamedQuery
(String name, Class<T> resultClass) Create an instance ofTypedQuery
for executing a Java Persistence query language named query.createNativeQuery
(String sqlString) Create an instance ofQuery
for executing a native SQL statement, e.g., for update or delete.createNativeQuery
(String sqlString, Class resultClass) Create an instance ofQuery
for executing a native SQL query.createNativeQuery
(String sqlString, String resultSetMapping) Create an instance ofQuery
for executing a native SQL query.createQuery
(String qlString) Create an instance ofQuery
for executing a Java Persistence query language statement.<T> TypedQuery
<T> createQuery
(String qlString, Class<T> resultClass) Create an instance ofTypedQuery
for executing a Java Persistence query language statement.<T> TypedQuery
<T> createQuery
(CriteriaQuery<T> criteriaQuery) Create an instance ofTypedQuery
for executing a criteria query.void
Remove the given entity from the persistence context, causing a managed entity to become detached.<T> T
Find by primary key.<T> T
Find by primary key, using the specified properties.<T> T
find
(Class<T> entityClass, Object primaryKey, LockModeType lockMode) Find by primary key and lock.<T> T
Find by primary key and lock, using the specified properties.void
flush()
Synchronize the persistence context to the underlying database.Return an instance ofCriteriaBuilder
for the creation ofCriteriaQuery
objects.Return the underlying provider object for theEntityManager
, if available.Return the entity manager factory for the entity manager.Get the flush mode that applies to all objects contained in the persistence context.getLockMode
(Object entity) Get the current lock mode for the entity instance.Return an instance ofMetamodel
interface for access to the metamodel of the persistence unit.Get the properties and hints and associated values that are in effect for the entity manager.<T> T
getReference
(Class<T> entityClass, Object primaryKey) Get an instance, whose state may be lazily fetched.Return the resource-levelEntityTransaction
object.boolean
isOpen()
Determine whether the entity manager is open.void
Indicate to the entity manager that a JTA transaction is active.void
lock
(Object entity, LockModeType lockMode) Lock an entity instance that is contained in the persistence context with the specified lock mode type.void
Lock an entity instance that is contained in the persistence context with the specified lock mode type and with specified properties.<T> T
merge
(T entity) Merge the state of the given entity into the current persistence context.void
Make an instance managed and persistent.void
Refresh the state of the instance from the database, overwriting changes made to the entity, if any.void
Refresh the state of the instance from the database, using the specified properties, and overwriting changes made to the entity, if any.void
refresh
(Object entity, LockModeType lockMode) Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type.void
Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type and with specified properties.void
Remove the entity instance.void
setFlushMode
(FlushModeType flushMode) Set the flush mode that applies to all objects contained in the persistence context.void
setProperty
(String propertyName, Object value) Set an entity manager property or hint.<T> T
Return an object of the specified type to allow access to the provider-specific API.
-
Method Details
-
persist
Make an instance managed and persistent.- Parameters:
entity
- entity instance- Throws:
EntityExistsException
- if the entity already exists. (If the entity already exists, theEntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.)IllegalArgumentException
- if the instance is not an entityTransactionRequiredException
- if invoked on a container-managed entity manager of typePersistenceContextType.TRANSACTION
and there is no transaction
-
merge
<T> T merge(T entity) Merge the state of the given entity into the current persistence context.- Parameters:
entity
- entity instance- Returns:
- the managed instance that the state was merged to
- Throws:
IllegalArgumentException
- if instance is not an entity or is a removed entityTransactionRequiredException
- if invoked on a container-managed entity manager of typePersistenceContextType.TRANSACTION
and there is no transaction
-
remove
Remove the entity instance.- Parameters:
entity
- entity instance- Throws:
IllegalArgumentException
- if the instance is not an entity or is a detached entityTransactionRequiredException
- if invoked on a container-managed entity manager of typePersistenceContextType.TRANSACTION
and there is no transaction
-
find
Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.- Parameters:
entityClass
- entity classprimaryKey
- primary key- Returns:
- the found entity instance or null if the entity does not exist
- Throws:
IllegalArgumentException
- if the first argument does not denote an entity type or the second argument is is not a valid type for that entity's primary key or is null
-
find
Find by primary key, using the specified properties. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there. If a vendor-specific property or hint is not recognized, it is silently ignored.- Parameters:
entityClass
- entity classprimaryKey
- primary keyproperties
- standard and vendor-specific properties and hints- Returns:
- the found entity instance or null if the entity does not exist
- Throws:
IllegalArgumentException
- if the first argument does not denote an entity type or the second argument is is not a valid type for that entity's primary key or is null- Since:
- Java Persistence 2.0
-
find
Find by primary key and lock. Search for an entity of the specified class and primary key and lock it with respect to the specified lock type. If the entity instance is contained in the persistence context, it is returned from there, and the effect of this method is the same as if the lock method had been called on the entity.If the entity is found within the persistence context and the lock mode type is pessimistic and the entity has a version attribute, the persistence provider must perform optimistic version checks when obtaining the database lock. If these checks fail, the
OptimisticLockException
will be thrown.If the lock mode type is pessimistic and the entity instance is found but cannot be locked:
- the
PessimisticLockException
will be thrown if the database locking failure causes transaction-level rollback - the
LockTimeoutException
will be thrown if the database locking failure causes only statement-level rollback
- Parameters:
entityClass
- entity classprimaryKey
- primary keylockMode
- lock mode- Returns:
- the found entity instance or null if the entity does not exist
- Throws:
IllegalArgumentException
- if the first argument does not denote an entity type or the second argument is not a valid type for that entity's primary key or is nullTransactionRequiredException
- if there is no transaction and a lock mode other than NONE is specifiedOptimisticLockException
- if the optimistic version check failsPessimisticLockException
- if pessimistic locking fails and the transaction is rolled backLockTimeoutException
- if pessimistic locking fails and only the statement is rolled backPersistenceException
- if an unsupported lock call is made- Since:
- Java Persistence 2.0
- the
-
find
<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties) Find by primary key and lock, using the specified properties. Search for an entity of the specified class and primary key and lock it with respect to the specified lock type. If the entity instance is contained in the persistence context, it is returned from there.If the entity is found within the persistence context and the lock mode type is pessimistic and the entity has a version attribute, the persistence provider must perform optimistic version checks when obtaining the database lock. If these checks fail, the
OptimisticLockException
will be thrown.If the lock mode type is pessimistic and the entity instance is found but cannot be locked:
- the
PessimisticLockException
will be thrown if the database locking failure causes transaction-level rollback - the
LockTimeoutException
will be thrown if the database locking failure causes only statement-level rollback
If a vendor-specific property or hint is not recognized, it is silently ignored.
Portable applications should not rely on the standard timeout hint. Depending on the database in use and the locking mechanisms used by the provider, the hint may or may not be observed.
- Parameters:
entityClass
- entity classprimaryKey
- primary keylockMode
- lock modeproperties
- standard and vendor-specific properties and hints- Returns:
- the found entity instance or null if the entity does not exist
- Throws:
IllegalArgumentException
- if the first argument does not denote an entity type or the second argument is not a valid type for that entity's primary key or is nullTransactionRequiredException
- if there is no transaction and a lock mode other thanNONE
is specifiedOptimisticLockException
- if the optimistic version check failsPessimisticLockException
- if pessimistic locking fails and the transaction is rolled backLockTimeoutException
- if pessimistic locking fails and only the statement is rolled backPersistenceException
- if an unsupported lock call is made- Since:
- Java Persistence 2.0
- the
-
getReference
Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, theEntityNotFoundException
is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw theEntityNotFoundException
whengetReference
is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.- Parameters:
entityClass
- entity classprimaryKey
- primary key- Returns:
- the found entity instance
- Throws:
IllegalArgumentException
- if the first argument does not denote an entity type or the second argument is not a valid type for that entity's primary key or is nullEntityNotFoundException
- if the entity state cannot be accessed
-
flush
void flush()Synchronize the persistence context to the underlying database.- Throws:
TransactionRequiredException
- if there is no transactionPersistenceException
- if the flush fails
-
setFlushMode
Set the flush mode that applies to all objects contained in the persistence context.- Parameters:
flushMode
- flush mode
-
getFlushMode
FlushModeType getFlushMode()Get the flush mode that applies to all objects contained in the persistence context.- Returns:
- flushMode
-
lock
Lock an entity instance that is contained in the persistence context with the specified lock mode type.If a pessimistic lock mode type is specified and the entity contains a version attribute, the persistence provider must also perform optimistic version checks when obtaining the database lock. If these checks fail, the
OptimisticLockException
will be thrown.If the lock mode type is pessimistic and the entity instance is found but cannot be locked:
- the
PessimisticLockException
will be thrown if the database locking failure causes transaction-level rollback - the
LockTimeoutException
will be thrown if the database locking failure causes only statement-level rollback
- Parameters:
entity
- entity instancelockMode
- lock mode- Throws:
IllegalArgumentException
- if the instance is not an entity or is a detached entityTransactionRequiredException
- if there is no transactionEntityNotFoundException
- if the entity does not exist in the database when pessimistic locking is performedOptimisticLockException
- if the optimistic version check failsPessimisticLockException
- if pessimistic locking fails and the transaction is rolled backLockTimeoutException
- if pessimistic locking fails and only the statement is rolled backPersistenceException
- if an unsupported lock call is made
- the
-
lock
Lock an entity instance that is contained in the persistence context with the specified lock mode type and with specified properties.If a pessimistic lock mode type is specified and the entity contains a version attribute, the persistence provider must also perform optimistic version checks when obtaining the database lock. If these checks fail, the
OptimisticLockException
will be thrown.If the lock mode type is pessimistic and the entity instance is found but cannot be locked:
- the
PessimisticLockException
will be thrown if the database locking failure causes transaction-level rollback - the
LockTimeoutException
will be thrown if the database locking failure causes only statement-level rollback
If a vendor-specific property or hint is not recognized, it is silently ignored.
Portable applications should not rely on the standard timeout hint. Depending on the database in use and the locking mechanisms used by the provider, the hint may or may not be observed.
- Parameters:
entity
- entity instancelockMode
- lock modeproperties
- standard and vendor-specific properties and hints- Throws:
IllegalArgumentException
- if the instance is not an entity or is a detached entityTransactionRequiredException
- if there is no transactionEntityNotFoundException
- if the entity does not exist in the database when pessimistic locking is performedOptimisticLockException
- if the optimistic version check failsPessimisticLockException
- if pessimistic locking fails and the transaction is rolled backLockTimeoutException
- if pessimistic locking fails and only the statement is rolled backPersistenceException
- if an unsupported lock call is made- Since:
- Java Persistence 2.0
- the
-
refresh
Refresh the state of the instance from the database, overwriting changes made to the entity, if any.- Parameters:
entity
- entity instance- Throws:
IllegalArgumentException
- if the instance is not an entity or the entity is not managedTransactionRequiredException
- if invoked on a container-managed entity manager of typePersistenceContextType.TRANSACTION
and there is no transactionEntityNotFoundException
- if the entity no longer exists in the database
-
refresh
Refresh the state of the instance from the database, using the specified properties, and overwriting changes made to the entity, if any.If a vendor-specific property or hint is not recognized, it is silently ignored.
- Parameters:
entity
- entity instanceproperties
- standard and vendor-specific properties and hints- Throws:
IllegalArgumentException
- if the instance is not an entity or the entity is not managedTransactionRequiredException
- if invoked on a container-managed entity manager of typePersistenceContextType.TRANSACTION
and there is no transactionEntityNotFoundException
- if the entity no longer exists in the database- Since:
- Java Persistence 2.0
-
refresh
Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type.If the lock mode type is pessimistic and the entity instance is found but cannot be locked:
- the
PessimisticLockException
will be thrown if the database locking failure causes transaction-level rollback - the
LockTimeoutException
will be thrown if the database locking failure causes only statement-level rollback.
- Parameters:
entity
- entity instancelockMode
- lock mode- Throws:
IllegalArgumentException
- if the instance is not an entity or the entity is not managedTransactionRequiredException
- if there is no transaction and if invoked on a container-managedEntityManager
instance withPersistenceContextType.TRANSACTION
or with a lock mode other thanNONE
EntityNotFoundException
- if the entity no longer exists in the databasePessimisticLockException
- if pessimistic locking fails and the transaction is rolled backLockTimeoutException
- if pessimistic locking fails and only the statement is rolled backPersistenceException
- if an unsupported lock call is made- Since:
- Java Persistence 2.0
- the
-
refresh
Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type and with specified properties.If the lock mode type is pessimistic and the entity instance is found but cannot be locked:
- the
PessimisticLockException
will be thrown if the database locking failure causes transaction-level rollback - the
LockTimeoutException
will be thrown if the database locking failure causes only statement-level rollback
If a vendor-specific property or hint is not recognized, it is silently ignored.
Portable applications should not rely on the standard timeout hint. Depending on the database in use and the locking mechanisms used by the provider, the hint may or may not be observed.
- Parameters:
entity
- entity instancelockMode
- lock modeproperties
- standard and vendor-specific properties and hints- Throws:
IllegalArgumentException
- if the instance is not an entity or the entity is not managedTransactionRequiredException
- if there is no transaction and if invoked on a container-managedEntityManager
instance withPersistenceContextType.TRANSACTION
or with a lock mode other thanNONE
EntityNotFoundException
- if the entity no longer exists in the databasePessimisticLockException
- if pessimistic locking fails and the transaction is rolled backLockTimeoutException
- if pessimistic locking fails and only the statement is rolled backPersistenceException
- if an unsupported lock call is made- Since:
- Java Persistence 2.0
- the
-
clear
void clear()Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted. -
detach
Remove the given entity from the persistence context, causing a managed entity to become detached. Unflushed changes made to the entity if any (including removal of the entity), will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it.- Parameters:
entity
- entity instance- Throws:
IllegalArgumentException
- if the instance is not an entity- Since:
- Java Persistence 2.0
-
contains
Check if the instance is a managed entity instance belonging to the current persistence context.- Parameters:
entity
- entity instance- Returns:
- boolean indicating if entity is in persistence context
- Throws:
IllegalArgumentException
- if not an entity
-
getLockMode
Get the current lock mode for the entity instance.- Parameters:
entity
- entity instance- Returns:
- lock mode
- Throws:
TransactionRequiredException
- if there is no transactionIllegalArgumentException
- if the instance is not a managed entity and a transaction is active- Since:
- Java Persistence 2.0
-
setProperty
Set an entity manager property or hint. If a vendor-specific property or hint is not recognized, it is silently ignored.- Parameters:
propertyName
- name of property or hintvalue
- value for property or hint- Throws:
IllegalArgumentException
- if the second argument is not valid for the implementation- Since:
- Java Persistence 2.0
-
getProperties
Get the properties and hints and associated values that are in effect for the entity manager. Changing the contents of the map does not change the configuration in effect.- Returns:
- map of properties and hints in effect for entity manager
- Since:
- Java Persistence 2.0
-
createQuery
Create an instance ofQuery
for executing a Java Persistence query language statement.- Parameters:
qlString
- a Java Persistence query string- Returns:
- the new query instance
- Throws:
IllegalArgumentException
- if the query string is found to be invalid
-
createQuery
Create an instance ofTypedQuery
for executing a criteria query.- Parameters:
criteriaQuery
- a criteria query object- Returns:
- the new query instance
- Throws:
IllegalArgumentException
- if the criteria query is found to be invalid- Since:
- Java Persistence 2.0
-
createQuery
Create an instance ofTypedQuery
for executing a Java Persistence query language statement. The select list of the query must contain only a single item, which must be assignable to the type specified by theresultClass
argument.- Parameters:
qlString
- a Java Persistence query stringresultClass
- the type of the query result- Returns:
- the new query instance
- Throws:
IllegalArgumentException
- if the query string is found to be invalid or if the query result is found to not be assignable to the specified type- Since:
- Java Persistence 2.0
-
createNamedQuery
Create an instance ofQuery
for executing a named query (in the Java Persistence query language or in native SQL).- Parameters:
name
- the name of a query defined in metadata- Returns:
- the new query instance
- Throws:
IllegalArgumentException
- if a query has not been defined with the given name or if the query string is found to be invalid
-
createNamedQuery
Create an instance ofTypedQuery
for executing a Java Persistence query language named query. The select list of the query must contain only a single item, which must be assignable to the type specified by theresultClass
argument.- Parameters:
name
- the name of a query defined in metadataresultClass
- the type of the query result- Returns:
- the new query instance
- Throws:
IllegalArgumentException
- if a query has not been defined with the given name or if the query string is found to be invalid or if the query result is found to not be assignable to the specified type- Since:
- Java Persistence 2.0
-
createNativeQuery
Create an instance ofQuery
for executing a native SQL statement, e.g., for update or delete.- Parameters:
sqlString
- a native SQL query string- Returns:
- the new query instance
-
createNativeQuery
Create an instance ofQuery
for executing a native SQL query.- Parameters:
sqlString
- a native SQL query stringresultClass
- the class of the resulting instance(s)- Returns:
- the new query instance
-
createNativeQuery
Create an instance ofQuery
for executing a native SQL query.- Parameters:
sqlString
- a native SQL query stringresultSetMapping
- the name of the result set mapping- Returns:
- the new query instance
-
joinTransaction
void joinTransaction()Indicate to the entity manager that a JTA transaction is active. This method should be called on a JTA application managed entity manager that was created outside the scope of the active transaction to associate it with the current JTA transaction.- Throws:
TransactionRequiredException
- if there is no transaction
-
unwrap
Return an object of the specified type to allow access to the provider-specific API. If the provider'sEntityManager
implementation does not support the specified class, thePersistenceException
is thrown.- Parameters:
cls
- the class of the object to be returned. This is normally either the underlyingEntityManager
implementation class or an interface that it implements.- Returns:
- an instance of the specified class
- Throws:
PersistenceException
- if the provider does not support the call- Since:
- Java Persistence 2.0
-
getDelegate
Object getDelegate()Return the underlying provider object for theEntityManager
, if available. The result of this method is implementation specific. Theunwrap
method is to be preferred for new applications.- Returns:
- underlying provider object for EntityManager
-
close
void close()Close an application-managed entity manager. After the close method has been invoked, all methods on theEntityManager
instance and anyQuery
andTypedQuery
objects obtained from it will throw theIllegalStateException
except forgetProperties
,getTransaction
, andisOpen
(which will return false). If this method is called when the entity manager is associated with an active transaction, the persistence context remains managed until the transaction completes.- Throws:
IllegalStateException
- if the entity manager is container-managed
-
isOpen
boolean isOpen()Determine whether the entity manager is open.- Returns:
- true until the entity manager has been closed
-
getTransaction
EntityTransaction getTransaction()Return the resource-levelEntityTransaction
object. TheEntityTransaction
instance may be used serially to begin and commit multiple transactions.- Returns:
- EntityTransaction instance
- Throws:
IllegalStateException
- if invoked on a JTA entity manager
-
getEntityManagerFactory
EntityManagerFactory getEntityManagerFactory()Return the entity manager factory for the entity manager.- Returns:
- EntityManagerFactory instance
- Throws:
IllegalStateException
- if the entity manager has been closed- Since:
- Java Persistence 2.0
-
getCriteriaBuilder
CriteriaBuilder getCriteriaBuilder()Return an instance ofCriteriaBuilder
for the creation ofCriteriaQuery
objects.- Returns:
- CriteriaBuilder instance
- Throws:
IllegalStateException
- if the entity manager has been closed- Since:
- Java Persistence 2.0
-
getMetamodel
Metamodel getMetamodel()Return an instance ofMetamodel
interface for access to the metamodel of the persistence unit.- Returns:
- Metamodel instance
- Throws:
IllegalStateException
- if the entity manager has been closed- Since:
- Java Persistence 2.0
-