Interface EntityHandler
- All Superinterfaces:
AutoCloseable
- All Known Subinterfaces:
EntityAgent, EntityManager
EntityManager and
EntityAgent. The status of an entity instance
returned by an operation declared by this interface
depends on the semantics of the subtype.
- For an
EntityAgent, there is no associated persistence context, and so every entity instance returned by any operation of the agent itself, or of any query object obtained from the agent, is in the detached state. Operations on an entity agent never return the same entity instance twice. - For an
EntityManager, every entity instance returned by any operation of the manager itself, or of any query object obtained from the manager, is in the managed state and belongs to the persistence context associated with the entity manager. The instance remains in the managed state until that entity manager is closed and its persistence context is destroyed unless the instance is explicitly detached via a call todetach()orclear(). AnEntityManageris required to ensure that if an entity instance representing a given record already exists in its associated persistence context, then exactly that instance is returned by every operation that returns an entity representing the record.
Note that, in a Jakarta EE container environment, a transaction-scoped entity manager which is accessed outside the scope of a container transaction is destroyed immediately after it is called. And so such an entity manager may appear to return unmanaged instances to its client. But this is merely a consequence of the extremely short lifetime of its persistence context.
Operations which return entity instances are, by default,
permitted to retrieve state from the second-level cache, if
any, or, in the case of an EntityManager, directly
from the persistence context, without directly accessing
the database. However, any such operation must respect:
- any lock mode requested as an
argument to the operation or by calling
TypedQuery.setLockMode(LockModeType), as well as - any cache mode given
as an optional argument or by
calling
setCacheRetrieveMode(CacheRetrieveMode)orTypedQuery.setCacheRetrieveMode(CacheRetrieveMode).
Thus, access to the database might be required even when the entity is available in the persistence context or in the second-level cache.
Outside the Jakarta EE container environment, the safest
and simplest way to obtain an EntityHandler is by
calling EntityManagerFactory.runInTransaction(Consumer) or
EntityManagerFactory.callInTransaction(Function).
Book book =
factory.callInTransaction(EntityAgent.class,
agent -> agent.get(Book.class, isbn))
- Since:
- 4.0
-
Method Summary
Modifier and TypeMethodDescription<C,T> T callWithConnection(ConnectionFunction<C, T> function) Call the given function and return its result using the database connection underlying thisEntityHandler.voidclose()Close an application-managedEntityHandler.<T> EntityGraph<T> createEntityGraph(Class<T> rootType) Create a new mutableEntityGraph, allowing programmatic definition of the graph.createNamedQuery(String name) Create an instance ofQueryfor executing a named query written in the Jakarta Persistence query language, usually anUPDATEorDELETEstatement, or in native SQL, usually anINSERT,UPDATE,MERGE, orDELETEstatement.<T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass) Create an instance ofTypedQueryfor executing a named query written in the Jakarta Persistence query language or in native SQL, returning instances of the given result class.createNamedStatement(String name) Create an instance ofStatementfor executing a namedUPDATEorDELETEstatement written in the Jakarta Persistence query language, or a named native SQL statement which returns a row count.Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database.createNativeQuery(String sqlString) Create an instance ofQueryfor executing a native SQL statement, usually anINSERT,UPDATE,MERGE, orDELETEstatement.<T> TypedQuery<T> createNativeQuery(String sqlString, ResultSetMapping<T> resultSetMapping) Create an instance ofTypedQueryfor executing a native SQL query, using the givenResultSetMappingto interpret the JDBC result set.<T> TypedQuery<T> createNativeQuery(String sqlString, Class<T> resultClass) Create an instance ofTypedQueryfor executing a native SQL query which produces a result set, returning instances of the given result class.createNativeQuery(String sqlString, String resultSetMapping) createNativeStatement(String sqlString) Create an instance ofStatementfor executing a native SQL statement which returns a row count, usually anINSERT,UPDATE,MERGE, orDELETEstatement.<T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery) Create an instance ofTypedQueryfor executing a criteria query.<T> TypedQuery<T> createQuery(CriteriaSelect<T> selectQuery) Create an instance ofTypedQueryfor executing a criteria select, which may be a union or intersection of top-level queries.<T> TypedQuery<T> createQuery(TypedQueryReference<T> reference) Create an instance ofTypedQueryfor executing a typed named query written in the Jakarta Persistence query language or in native SQL.createQuery(String qlString) Create an instance ofQueryfor executing a Jakarta Persistence query language statement, usually anUPDATEorDELETEstatement.<T> TypedQuery<T> createQuery(String qlString, EntityGraph<T> resultGraph) Create an instance ofTypedQueryfor executing a Jakarta Persistence query languageSELECTstatement, specifying anEntityGraphwhich is interpreted as a load graph.<T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass) Create an instance ofTypedQueryfor executing a Jakarta Persistence query languageSELECTstatement and returning instances of the given result class.createStatement(CriteriaStatement<?> statement) Create an instance ofStatementfor executing a criteria statement.createStatement(StatementReference reference) Create an instance ofStatementfor executing a named statement written in the Jakarta Persistence query language or in native SQL.createStatement(String qlString) createStoredProcedureQuery(String procedureName) Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database.createStoredProcedureQuery(String procedureName, Class<?>... resultClasses) Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database, explicitly specifying the result class for every result set returned by the stored procedure.createStoredProcedureQuery(String procedureName, String... resultSetMappings) Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database, explicitly specifying the name of a result set mapping for every result set returned by the stored procedure.<T> Tfind(EntityGraph<T> graph, Object id, FindOption... options) Retrieve an instance of the root entity of the givenEntityGraphrepresenting the record with the given identifier, or returnnullif there is no such record in the database, using the specified options and interpreting theEntityGraphas a load graph.<T> TRetrieve an entity representing the record with the given identifier, or returnnullif there is no such record in the database.<T> Tfind(Class<T> entityClass, Object id, FindOption... options) Retrieve an entity representing the record with the given identifier, or returnnullif there is no such record in the database, using the specified options.<T> List<T> findMultiple(EntityGraph<T> graph, List<?> ids, FindOption... options) Retrieve entity instances representing the records with the given identifiers of the root entity of the givenEntityGraph, using the specified options and interpreting theEntityGraphas a load graph, returning entity instances in a list where the position of an instance in the list matches the position of its identifier in the given array, and the list contains a null value if there is no record matching a given identifier.<T> List<T> findMultiple(Class<T> entityClass, List<?> ids, FindOption... options) Retrieve entity instances representing the records with the given identifiers, using the specified options, returning the instances in a list where the position of an instance in the list matches the position of its identifier in the given array, and the list contains a null value if there is no record matching a given identifier.<T> Tget(EntityGraph<T> graph, Object id, FindOption... options) Retrieve an entity representing the record with the given identifier, fetching associations specified by the given load graph, and using the specified options.<T> TRetrieve an entity representing the record with the given identifier.<T> Tget(Class<T> entityClass, Object id, FindOption... options) Retrieve an entity representing the record with the given identifier, using the specified options.The cache retrieval mode for thisEntityHandler.The cache storage mode for thisEntityHandler.Obtain an instance ofCriteriaBuilderwhich may be used to constructCriteriaQueryobjects.<T> EntityGraph<T> getEntityGraph(Class<T> rootType, String graphName) Obtain a mutable copy of the namedEntityGraphwhose root type is exactly the given entity type.EntityGraph<?> getEntityGraph(String graphName) Obtain a mutable copy of the namedEntityGraph.<T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) Return all namedEntityGraphs that are defined for the given entity class type.The entity manager factory which created thisEntityHandler.Obtain an instance of theMetamodelinterface which provides access to metamodel objects describing the managed types belonging to the persistence unit.<T> List<T> getMultiple(EntityGraph<T> graph, List<?> ids, FindOption... options) Retrieve entity instances representing the records with the given identifiers of the root entity of the given load graph, using the specified options, and returning the instances in a list where the position of an instance in the list matches the position of its identifier in the given array, and fetching associations specified by the load graph.<T> List<T> getMultiple(Class<T> entityClass, List<?> ids, FindOption... options) Retrieve entity instances representing the records with the given identifiers, using the specified options, and returning the instances in a list where the position of an instance in the list matches the position of its identifier in the given array.The properties and hints and their associated values which are in effect for thisEntityHandler.Return the resource-levelEntityTransactionobject.booleanisOpen()Determine whether theEntityHandleris open.<C> voidrunWithConnection(ConnectionConsumer<C> action) Execute the given action using the database connection underlying thisEntityHandler.voidsetCacheRetrieveMode(CacheRetrieveMode cacheRetrieveMode) Set the default cache retrieval mode for thisEntityHandler.voidsetCacheStoreMode(CacheStoreMode cacheStoreMode) Set the default cache storage mode for thisEntityHandler.voidsetProperty(String propertyName, Object value) Set anEntityHandler-scoped property or hint.<T> TReturn an object of the specified type to allow access to a provider-specific API.
-
Method Details
-
get
Retrieve an entity representing the record with the given identifier.- Parameters:
entityClass- The class of the entity to retrieveid- The identifier of the entity to retrieve- Returns:
- an entity instance with the given identifier
- Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, or if the given identifier is not a non-null instance of the identifier type of the given entity classEntityNotFoundException- if no record with the given identifier exists in the databasePersistenceException- if the record could not be read from the database- Since:
- 4.0
- API note:
- Conceptually similar to find(Class, Object), except this form throws EntityNotFoundException instead of returning null.
-
get
Retrieve an entity representing the record with the given identifier, using the specified options. If the given options include aLockModeType, obtain the lock level specified by the given lock mode.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
entityClass- The class of the entity to retrieveid- The identifier of the entity to retrieveoptions- Standard and vendor-specific options- Returns:
- an entity instance with the given identifier
- Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, or if the given identifier is not a non-null instance of the identifier type of the given entity classEntityNotFoundException- if no record with the given identifier exists in the databasePersistenceException- if a given lock mode type is not supported for the given entity class or if the record could not be read from the database- Since:
- 4.0
- API note:
- Conceptually similar to find(Class, Object), except this form throws EntityNotFoundException instead of returning null.
-
get
Retrieve an entity representing the record with the given identifier, fetching associations specified by the given load graph, and using the specified options. If the given options include aLockModeType, obtain the lock level specified by the given lock mode.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
graph- The load graphid- The identifier of the entity to retrieveoptions- Standard and vendor-specific options- Returns:
- an entity instance with the given identifier
- Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, or if the given identifier is not a non-null instance of the identifier type of the given entity classEntityNotFoundException- if no record with the given identifier exists in the databasePersistenceException- if a given lock mode type is not supported for the given entity class or if the record could not be read from the database- Since:
- 4.0
- API note:
- Conceptually similar to find(Class, Object), except this form throws EntityNotFoundException instead of returning null.
-
getMultiple
Retrieve entity instances representing the records with the given identifiers, using the specified options, and returning the instances in a list where the position of an instance in the list matches the position of its identifier in the given array. If the given options include aLockModeType, obtain the lock level specified by the given lock mode.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
entityClass- The class of the entity to retrieveids- The identifiers of the entities to retrieveoptions- Standard and vendor-specific options- Returns:
- an ordered list of entity instances
- Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, or if one of the given identifiers is not a non-null instance of the identifier type of the given entity classEntityNotFoundException- if no record exists in the database for one of the given identifiersPersistenceException- if a given lock mode type is not supported for the given entity class or if a record could not be read from the database- Since:
- 4.0
- API note:
- Conceptually similar to findMultiple(Class, List, FindOption...), except this form throws EntityNotFoundException instead of returning nulls.
-
getMultiple
Retrieve entity instances representing the records with the given identifiers of the root entity of the given load graph, using the specified options, and returning the instances in a list where the position of an instance in the list matches the position of its identifier in the given array, and fetching associations specified by the load graph.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
graph- The load graphids- The identifiers of the entities to retrieveoptions- Standard and vendor-specific options- Returns:
- an ordered list of entity instances
- Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, or if one of the given identifiers is not a non-null instance of the identifier type of the given entity classEntityNotFoundException- if no record exists in the database for one of the given identifiersPersistenceException- if a given lock mode type is not supported for the given entity class or if a record could not be read from the database- Since:
- 4.0
- API note:
- Conceptually similar to findMultiple(Class, List, FindOption...), except this form throws EntityNotFoundException instead of returning nulls.
-
find
Retrieve an entity representing the record with the given identifier, or returnnullif there is no such record in the database.- Parameters:
entityClass- The class of the entity to retrieveid- The identifier of the entity to retrieve- Returns:
- an entity instance with the given identifier,
or
nullif there is no matching record in the database - Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, or if the given identifier is not a non-null instance of the identifier type of the given entity classPersistenceException- if the record could not be read from the database- Since:
- 1.0
-
find
Retrieve an entity representing the record with the given identifier, or returnnullif there is no such record in the database, using the specified options. If the given options include aLockModeType, obtain the lock level specified by the given lock mode.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
entityClass- The class of the entity to retrieveid- The identifier of the entity to retrieveoptions- Standard and vendor-specific options- Returns:
- an entity instance with the given identifier,
or
nullif there is no matching record in the database - Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, if the given identifier is not a non-null instance of the identifier type of the given entity class, or if the given options are contradictoryTransactionRequiredException- if any lock mode other thanNONEis specified and there is no transaction associated with this handlerOptimisticLockException- if an optimistic version check failsPessimisticLockException- if a pessimistic lock could not be obtained and the transaction is rolled backLockTimeoutException- if a pessimistic lock could not be obtained and only the statement is rolled backPersistenceException- if a given lock mode type is not supported for the given entity class or if the record could not be read from the database- Since:
- 3.2
-
find
Retrieve an instance of the root entity of the givenEntityGraphrepresenting the record with the given identifier, or returnnullif there is no such record in the database, using the specified options and interpreting theEntityGraphas a load graph. If the given options include aLockModeType, obtain the lock level specified by the given lock mode.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
graph- The load graphid- The identifier of the entity to retrieveoptions- Standard and vendor-specific options- Returns:
- an entity instance with the given identifier,
or
nullif there is no matching record in the database - Throws:
IllegalArgumentException- if the root entity of the given graph is not an entity class belonging to the persistence unit, if the given identifier is not a non-null instance of the identifier type of the given entity class, or if the given options are contradictoryTransactionRequiredException- if any lock mode other thanNONEis specified and there is no transaction associated with this handlerOptimisticLockException- if an optimistic version check failsPessimisticLockException- if a pessimistic lock could not be obtained and the transaction is rolled backLockTimeoutException- if a pessimistic lock could not be obtained and only the statement is rolled backPersistenceException- if a given lock mode type is not supported for the root entity of the given graph or if the record could not be read from the database- Since:
- 3.2
-
findMultiple
Retrieve entity instances representing the records with the given identifiers, using the specified options, returning the instances in a list where the position of an instance in the list matches the position of its identifier in the given array, and the list contains a null value if there is no record matching a given identifier. If the given options include aLockModeType, obtain the lock level specified by the given lock mode.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
entityClass- The class of the entity to retrieveids- The identifiers of the entities to retrieveoptions- Standard and vendor-specific options- Returns:
- an ordered list of entity instances with the
given identifiers, with
nullin positions where there is no matching record in the database - Throws:
IllegalArgumentException- if the given class is not an entity class belonging to the persistence unit, if one of the given identifiers is not a non-null instance of the identifier type of the given entity class, or if the given options are contradictoryTransactionRequiredException- if any lock mode other thanNONEis specified and there is no transaction associated with this handlerOptimisticLockException- if an optimistic version check failsPessimisticLockException- if a pessimistic lock could not be obtained and the transaction is rolled backLockTimeoutException- if a pessimistic lock could not be obtained and only the statement is rolled backPersistenceException- if a given lock mode type is not supported for the given entity class or if a record could not be read from the database- Since:
- 4.0
-
findMultiple
Retrieve entity instances representing the records with the given identifiers of the root entity of the givenEntityGraph, using the specified options and interpreting theEntityGraphas a load graph, returning entity instances in a list where the position of an instance in the list matches the position of its identifier in the given array, and the list contains a null value if there is no record matching a given identifier. If the given options include aLockModeType, obtain the lock level specified by the given lock mode.If an implementation does not recognize a given vendor-specific option, it must silently ignore the option.
Portable applications should not rely on the standard timeout option. Depending on the database in use and the locking mechanisms used by the provider, this option may or may not be observed.
- Parameters:
graph- The load graphids- The identifiers of the entities to retrieveoptions- Standard and vendor-specific options- Returns:
- an ordered list of entity instances with the
given identifiers, with
nullin positions where there is no matching record in the database - Throws:
IllegalArgumentException- if the root entity of the given graph is not an entity class belonging to the persistence unit, if one of the given identifiers is not a non-null instance of the identifier type of the given entity class, or if the given options are contradictoryTransactionRequiredException- if any lock mode other thanNONEis specified and there is no transaction associated with this handlerOptimisticLockException- if an optimistic version check failsPessimisticLockException- if a pessimistic lock could not be obtained and the transaction is rolled backLockTimeoutException- if a pessimistic lock could not be obtained and only the statement is rolled backPersistenceException- if a given lock mode type is not supported for the root entity of the given graph or if a record could not be read from the database- Since:
- 4.0
-
setCacheRetrieveMode
Set the default cache retrieval mode for thisEntityHandler.- Parameters:
cacheRetrieveMode- The new default cache retrieval mode- Since:
- 3.2
-
setCacheStoreMode
Set the default cache storage mode for thisEntityHandler.- Parameters:
cacheStoreMode- The new default cache storage mode- Since:
- 3.2
-
getCacheRetrieveMode
CacheRetrieveMode getCacheRetrieveMode()The cache retrieval mode for thisEntityHandler.- Since:
- 3.2
-
getCacheStoreMode
-
setProperty
Set anEntityHandler-scoped property or hint. If a vendor-specific property or hint is not recognized, it is silently ignored.- Parameters:
propertyName- The name of the property or hintvalue- The value for the property or hint- Throws:
IllegalArgumentException- if the property or hint name is recognized by the implementation, but the second argument is not a valid value for that hint- Since:
- 2.0
-
getProperties
-
createStatement
- Parameters:
qlString- A Jakarta Persistence statement string- Returns:
- An instance of
Statementwhich may be used to execute the given statement - Throws:
IllegalArgumentException- if the query string is found to be invalid- Since:
- 4.0
-
createQuery
Create an instance ofQueryfor executing a Jakarta Persistence query language statement, usually anUPDATEorDELETEstatement.If the given query is a
SELECTstatement, the query results might be packaged as arrays:- if the query contains a single item in its select list, each query result is the value of that item, or
- otherwise, if the query contains multiple items in
its select list, each query result is packaged in
an array of type
Object[], with the array elements corresponding by position with the items of the select list.
- Parameters:
qlString- A Jakarta Persistence query string- Returns:
- An instance of
Querywhich may be used to execute the given query - Throws:
IllegalArgumentException- if the query string is found to be invalid- API note:
- For backward compatibility, the returned object
may be used to directly execute any kind of statement or
query via its deprecated methods. Newly written code
should call:
createStatement(String)to obtain aStatement,- an overload which specifies a
result class
or entity graph obtain a
TypedQuery, or asStatement()orofType()to obtain aStatementorTypedQuery, respectively, from the object returned by this method.
-
createQuery
Create an instance ofTypedQueryfor executing a criteria query.- Parameters:
criteriaQuery- A criteria query object- Returns:
- An instance of
Querywhich may be used to execute the given query - Throws:
IllegalArgumentException- if the criteria query is found to be invalid- Since:
- 2.0
-
createQuery
Create an instance ofTypedQueryfor executing a criteria select, which may be a union or intersection of top-level queries.- Parameters:
selectQuery- A criteria select query object- Returns:
- An instance of
Querywhich may be used to execute the given query - Throws:
IllegalArgumentException- if the criteria query is found to be invalid- Since:
- 3.2
-
createStatement
Create an instance ofStatementfor executing a criteria statement.- Parameters:
statement- A criteria statement object- Returns:
- An instance of
Statementwhich may be used to execute the given statement - Throws:
IllegalArgumentException- if the statement is found to be invalid- Since:
- 4.0
-
createQuery
Create an instance ofTypedQueryfor executing a Jakarta Persistence query languageSELECTstatement and returning instances of the given result class. Either:- the select list of the query contains only a single item, which must be assignable to the result class,
- the result class is
Object[].class, or - the result class is a non-abstract class or record type with a constructor with the same number of parameters as the query has items in its select list, and the constructor parameter types exactly match the types of the corresponding items in the select list.
In the first case, each query result is returned directly to the caller. In the second case, each query result is packaged in an array with the array elements corresponding by position with the items of the query select list. In the third case, each query result is automatically packaged in a new instance of the result class by calling the matching constructor.
- Parameters:
qlString- A Jakarta Persistence query stringresultClass- The result class- Returns:
- An instance of
Querywhich may be used to execute the given query - 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 and the specified type does not have a suitable constructor- Since:
- 2.0
-
createQuery
Create an instance ofTypedQueryfor executing a Jakarta Persistence query languageSELECTstatement, specifying anEntityGraphwhich is interpreted as a load graph. The select list of the query must contain only a single item, which must be assignable to the root type of the given entity graph.- Parameters:
qlString- A Jakarta Persistence query stringresultGraph- The load graph- Returns:
- An instance of
Querywhich may be used to execute the given query - Throws:
IllegalArgumentException- if the query string is found to be invalid, or if the query result is found to not be assignable to the root type of the entity graph- Since:
- 4.0
-
createNamedStatement
Create an instance ofStatementfor executing a namedUPDATEorDELETEstatement written in the Jakarta Persistence query language, or a named native SQL statement which returns a row count.- Parameters:
name- The name of a statement defined in metadata- Returns:
- An instance of
Statementwhich may be used to execute the named statement - Throws:
IllegalArgumentException- if a query has not been defined with the given name, or if the query string is found to be invalid- Since:
- 4.0
- See Also:
-
createNamedQuery
Create an instance ofQueryfor executing a named query written in the Jakarta Persistence query language, usually anUPDATEorDELETEstatement, or in native SQL, usually anINSERT,UPDATE,MERGE, orDELETEstatement.- If the named query is a
SELECTstatement written in the Jakarta Persistence query language, the query results are packaged according to the result class specified by theNamedQueryannotation, or - If the named query is written in native SQL and
returns a result set, the query results are
interpreted and packaged according to the
result class
and result set mapping specified by the
NamedNativeQueryannotation.
- Parameters:
name- The name of a query defined in metadata- Returns:
- An instance of
Querywhich may be used to execute the given query - Throws:
IllegalArgumentException- if a query has not been defined with the given name, or if the query string is found to be invalid- Since:
- 1.0
- See Also:
- If the named query is a
-
createNamedQuery
Create an instance ofTypedQueryfor executing a named query written in the Jakarta Persistence query language or in native SQL, returning instances of the given result class.- If the named query is written in the Jakarta Persistence
query language, the result class is interpreted as if it
were an argument of
createQuery(String, Class). - If the named query is written in native SQL, the result
class is interpreted as if it were an argument of
createNativeQuery(String, Class).
The given result class overrides any result class specified by the
NamedQueryannotation orNamedNativeQueryannotation which declares the named query.- Parameters:
name- The name of a query defined in metadataresultClass- The type of the query result- Returns:
- An instance of
Querywhich may be used to execute the given query - Throws:
IllegalArgumentException- if a query has not been defined with the given name, 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:
- 2.0
- If the named query is written in the Jakarta Persistence
query language, the result class is interpreted as if it
were an argument of
-
createStatement
Create an instance ofStatementfor executing a named statement written in the Jakarta Persistence query language or in native SQL.- Parameters:
reference- a reference to the query defined in metadata- Returns:
- the new query instance
- Throws:
IllegalArgumentException- if a named query has not been defined, or if the query string is found to be invalid- Since:
- 4.0
- See Also:
-
createQuery
Create an instance ofTypedQueryfor executing a typed named query written in the Jakarta Persistence query language or in native SQL.- If the named query is a
SELECTstatement written in the Jakarta Persistence query language, the query results are packaged according to the result class specified by theNamedQueryannotation, or - If the named query is written in native SQL and
returns a result set, the query results are
interpreted and packaged according to the
result class
and result set mapping specified by the
NamedNativeQueryannotation.
- Parameters:
reference- A reference to the query defined in metadata- Returns:
- An instance of
TypedQuerywhich may be used to execute the given query - Throws:
IllegalArgumentException- if a query has not been defined, 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:
- 3.2
- See Also:
- If the named query is a
-
createNativeStatement
-
createNativeQuery
Create an instance ofQueryfor executing a native SQL statement, usually anINSERT,UPDATE,MERGE, orDELETEstatement.If the given query produces a result set, the query results might be packaged as arrays:
- if the query contains a single column in its result set, each query result is the value of that column, or
- otherwise, if the query contains multiple columns
in its result set, each query result is packaged in
an array of type
Object[], with the array elements corresponding by position with the columns of the select list.
Column values are obtained according to the default type mappings defined by the JDBC specification.
- Parameters:
sqlString- A native SQL query string- Returns:
- An instance of
Querywhich may be used to execute the given query - Since:
- 1.0
- API note:
- This overload is most appropriate when used to
execute a statement which returns a row count. For a
SELECTstatement, an overload which specifies a result class or result set mapping is usually more appropriate.
-
createNativeQuery
Create an instance ofTypedQueryfor executing a native SQL query which produces a result set, returning instances of the given result class. Either:- the result class is an entity class and is interpreted as a managed entity result with implicit field mappings determined by the names of the columns in the result set and the object/relational mapping of the entity,
- the result class is the class of a basic type and the result set must have a single column which is interpreted as a scalar result,
- the result class is a non-
abstractclass or record type with a constructor with the same number of parameters as the result set has columns, and is interpreted as a constructor result including all the columns of the result set, or - the result class is
Object[].classand each query result is packaged in an array of typeObject[], with the array elements corresponding by position with the columns of the select list and column values obtained according to the default type mappings defined by the JDBC specification.
- Parameters:
sqlString- A native SQL query stringresultClass- The type of the query result- Returns:
- An instance of
Querywhich may be used to execute the given query - Since:
- 1.0
-
createNativeQuery
Create an instance ofQueryfor executing a native SQL query, using the mapping with the given name to interpret the JDBC result set.- Parameters:
sqlString- A native SQL query stringresultSetMapping- The name of the result set mapping- Returns:
- An instance of
Querywhich may be used to execute the given query - Since:
- 1.0
- See Also:
- API note:
- Use of this overloaded form of the method results in a
type cast of each query result in client code. As an alternative,
obtain a typed reference to the mapping from the static metamodel
and use
createNativeQuery(String, ResultSetMapping).
-
createNativeQuery
Create an instance ofTypedQueryfor executing a native SQL query, using the givenResultSetMappingto interpret the JDBC result set.- Parameters:
sqlString- A native SQL query stringresultSetMapping- The result set mapping- Returns:
- An instance of
Querywhich may be used to execute the given query - Since:
- 4.0
-
createNamedStoredProcedureQuery
Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database.Parameters must be registered before the stored procedure can be executed.
If the stored procedure returns one or more result sets, any result set is returned as a list of type
Object[].- Parameters:
name- The name assigned to the stored procedure query in metadata- Returns:
- An instance of
StoredProcedureQuerywhich may be used to execute the stored procedure - Throws:
IllegalArgumentException- if no query has been defined with the given name- Since:
- 2.1
-
createStoredProcedureQuery
Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database.Parameters must be registered before the stored procedure can be executed.
If the stored procedure returns one or more result sets, any result set is returned as a list of type
Object[].- Parameters:
procedureName- The name of the stored procedure in the database- Returns:
- An instance of
StoredProcedureQuerywhich may be used to execute the stored procedure - Throws:
IllegalArgumentException- if a stored procedure of the given name does not exist (or if query execution will fail)- Since:
- 2.1
-
createStoredProcedureQuery
Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database, explicitly specifying the result class for every result set returned by the stored procedure.Parameters must be registered before the stored procedure can be executed.
The given result classes must be specified in the order in which the corresponding result sets are returned by the stored procedure invocation. For each given result class, either:
- the result class is an entity class and is interpreted as a managed entity result with implicit field mappings determined by the names of the columns in the result set and the object/relational mapping of the entity,
- the result class is the class of a basic type and the result set must have a single column which is interpreted as a scalar result, or
- the result class must be a non-abstract class or record type with a constructor with the same number of parameters as the result set has columns, and is interpreted as a constructor result including all the columns of the result set.
- Parameters:
procedureName- The name of the stored procedure in the databaseresultClasses- The classes to which the result sets produced by the stored procedure are mapped- Returns:
- An instance of
StoredProcedureQuerywhich may be used to execute the stored procedure - Throws:
IllegalArgumentException- if a stored procedure of the given name does not exist (or if query execution will fail)- Since:
- 2.1
- API note:
- Use of this overloaded form of the method results
in a redundant type cast of each query result in client code.
Instead, use
createStoredProcedureQuery(String)and pass each result class individually as an argument toStoredProcedureQuery.getResultList(Class),StoredProcedureQuery.getSingleResult(Class), orStoredProcedureQuery.getSingleResultOrNull(Class).
-
createStoredProcedureQuery
Create an instance ofStoredProcedureQueryfor executing a stored procedure in the database, explicitly specifying the name of a result set mapping for every result set returned by the stored procedure.Parameters must be registered before the stored procedure can be executed.
The given result set mappings must be specified in the order in which the corresponding result sets are returned by the stored procedure invocation.
- Parameters:
procedureName- The name of the stored procedure in the databaseresultSetMappings- The names of the result set mappings to be used to map result sets returned by the stored procedure- Returns:
- An instance of
StoredProcedureQuerywhich may be used to execute the stored procedure - Throws:
IllegalArgumentException- if a stored procedure or result set mapping of the given name does not exist (or the query execution will fail)- Since:
- 2.1
- See Also:
- API note:
- Use of this overloaded form of the method results
in a type cast of each query result in client code. As an
alternative, use
createStoredProcedureQuery(String)and pass each result mapping individually as an argument toStoredProcedureQuery.getResultList(ResultSetMapping),StoredProcedureQuery.getSingleResult(ResultSetMapping), orStoredProcedureQuery.getSingleResultOrNull(ResultSetMapping).
-
unwrap
Return an object of the specified type to allow access to a provider-specific API. If the provider implementation ofEntityHandlerdoes not support the given type, thePersistenceExceptionis thrown.- Parameters:
type- The class of the object to be returned. This is usually either the underlying class implementingEntityHandleror an interface it implements- Returns:
- An instance of the specified class
- Throws:
PersistenceException- if the provider does not support the given type- Since:
- 2.0
-
close
void close()Close an application-managedEntityHandler.After invocation of
close(), every method of theEntityHandlerinstance and of any instance ofQuery,TypedQuery, orStoredProcedureQueryobtained from it throws theIllegalStateException, except forgetProperties(),getTransaction(), andisOpen()(which returns false).If this method is called when the
EntityHandleris joined to an active transaction, any managed entities remain managed until the transaction completes.- Specified by:
closein interfaceAutoCloseable- Throws:
IllegalStateException- if theEntityHandleris container-managed- Since:
- 1.0
-
isOpen
boolean isOpen()Determine whether theEntityHandleris open.- Returns:
- true until the
EntityHandlerhas been closed - Since:
- 1.0
-
getTransaction
EntityTransaction getTransaction()Return the resource-levelEntityTransactionobject. TheEntityTransactioninstance may be used serially to begin and commit multiple transactions.- Returns:
- An instance of
EntityTransaction - Throws:
IllegalStateException- if invoked on a JTA entity manager or entity agent- Since:
- 1.0
-
getEntityManagerFactory
EntityManagerFactory getEntityManagerFactory()The entity manager factory which created thisEntityHandler.- Returns:
- The
EntityManagerFactory - Throws:
IllegalStateException- if theEntityHandlerhas been closed- Since:
- 2.0
-
getCriteriaBuilder
CriteriaBuilder getCriteriaBuilder()Obtain an instance ofCriteriaBuilderwhich may be used to constructCriteriaQueryobjects.- Returns:
- an instance of
CriteriaBuilder - Throws:
IllegalStateException- if theEntityHandlerhas been closed- Since:
- 2.0
- See Also:
-
getMetamodel
Metamodel getMetamodel()Obtain an instance of theMetamodelinterface which provides access to metamodel objects describing the managed types belonging to the persistence unit.- Returns:
- An instance of
Metamodel - Throws:
IllegalStateException- if theEntityHandlerhas been closed- Since:
- 2.0
-
createEntityGraph
Create a new mutableEntityGraph, allowing programmatic definition of the graph.- Parameters:
rootType- the root entity type of the new graph- Returns:
- a trivial entity graph with only a root node
- Since:
- 2.1
- See Also:
-
getEntityGraph
Obtain a mutable copy of the namedEntityGraph.- Parameters:
graphName- the name of an existing entity graph- Returns:
- the entity graph with the given name
- Throws:
IllegalArgumentException- if there is no entity graph with the given name- Since:
- 2.1
-
getEntityGraph
Obtain a mutable copy of the namedEntityGraphwhose root type is exactly the given entity type.- Parameters:
rootType- the root entity type of the graphgraphName- the name of an existing entity graph- Returns:
- the entity graph with the given name
- Throws:
IllegalArgumentException- if there is no entity graph with the given name, or if the entity graph with the given name does not have exactly the given root entity type- Since:
- 4.0
-
getEntityGraphs
Return all namedEntityGraphs that are defined for the given entity class type.- Parameters:
entityClass- An entity class- Returns:
- A list of all entity graphs whose root entity type is a supertype of the given entity class
- Throws:
IllegalArgumentException- if the class is not an entity- Since:
- 2.1
-
runWithConnection
Execute the given action using the database connection underlying thisEntityHandler. Usually, the connection is a JDBC connection, but a provider might support some other native connection type, and is not required to supportjava.sql.Connection. If thisEntityHandleris associated with a transaction, the action is executed in the context of the transaction. The given action should close any resources it creates but should not close the connection itself, nor commit or roll back the transaction. If the given action throws an exception, the persistence provider must mark the transaction for rollback.entityManager.runWithConnection((Connection connection) -> { try (var statement = connection.createStatement()) { statement.execute("set constraints all deferred"); } });- Type Parameters:
C- The connection type, usuallyjava.sql.Connection- Parameters:
action- The action to execute- Throws:
PersistenceException- wrapping the checkedExceptionthrown byConnectionConsumer.accept(C), if any- Since:
- 3.2
-
callWithConnection
Call the given function and return its result using the database connection underlying thisEntityHandler. Usually, the connection is a JDBC connection, but a provider might support some other native connection type, and is not required to supportjava.sql.Connection. If thisEntityHandleris associated with a transaction, the function is executed in the context of the transaction. The given function should close any resources it creates but should not close the connection itself, nor commit or roll back the transaction. If the given action throws an exception, the persistence provider must mark the transaction for rollback.LocalTime currentTimeOnServer = entityManager.callWithConnection((Connection connection) -> { try (var statement = connection.createStatement()) { try (var resultSet = statement.executeQuery("select current_time")) { resultSet.next(); return resultSet.getObject(1, LocalTime.class); } } });- Type Parameters:
C- The connection type, usuallyjava.sql.ConnectionT- The type of result returned by the function- Parameters:
function- The function to call- Returns:
- The value returned by
ConnectionFunction.apply(C). - Throws:
PersistenceException- wrapping the checkedExceptionthrown byConnectionFunction.apply(C), if any- Since:
- 3.2
-