Running JPA Queries
The Queryjakarta.persistence.QueryInterface used to control query execution. interface defines two methods for running SELECT queries:
Query.getSingleResultjakarta.persistence.Query.getSingleResult()Execute a SELECT query that returns a single untyped result.(): Use when exactly one result object is expected.Query.getResultListjakarta.persistence.Query.getResultList()Execute a SELECT query and return the query results as an untyped List<E> .(): Use in any other case.
Similarly, the TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries. interface defines the following methods:
TypedQuery.getSingleResultjakarta.persistence.TypedQuery.getSingleResult()Execute a SELECT query that returns a single result.(): Use when exactly one result object is expected.TypedQuery.getResultListjakarta.persistence.TypedQuery.getResultList()Execute a SELECT query and return the query results as a typed List<X> .(): Use in any other case.
In addition, the Query interface defines a method for running DELETE and UPDATE queries:
Query.executeUpdatejakarta.persistence.Query.executeUpdate()Execute an update or delete statement.(): Use to runDELETEandUPDATEqueries.
This page covers the following topics:
Ordinary query execution (with getResultList())Single-result query execution (with getSingleResult())DELETE and UPDATE query execution (with executeUpdate())Ordinary query execution (with getResultList())
The following query retrieves all the Country objects in the database. Use the getResultList()jakarta.persistence.TypedQuery.getResultList()Execute a SELECT query and return the query results as a typed List<X> . method to run this query, as it can return multiple objects:
TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries.<Country> query = em.createQueryjakarta.persistence.EntityManager.createQuery(String,Class)Create an instance of TypedQuery<X> for executing a Jakarta Persistence query language statement.("SELECT c FROM Country c", Country.class); List<Country> results = query.getResultListjakarta.persistence.TypedQuery.getResultList()Execute a SELECT query and return the query results as a typed List<X> .();
Both the Queryjakarta.persistence.QueryInterface used to control query execution. and TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries. interfaces define a getResultList() method. The Query version returns a list of a raw (non-generic) type, while the TypedQuery version returns a list of a parameterized (generic) type:
Queryjakarta.persistence.QueryInterface used to control query execution. query = em.createQueryjakarta.persistence.EntityManager.createQuery(String)Create an instance of Query for executing a Jakarta Persistence query language statement.("SELECT c FROM Country c"); List results = query.getResultListjakarta.persistence.Query.getResultList()Execute a SELECT query and return the query results as an untyped List<E> .();
Casting the results object to a parameterized type, such as List<Country>, causes a compilation warning. To avoid this warning, use the TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries. interface, which makes casting unnecessary.
A query result collection works like any other Java collection. For example, you can iterate over a result collection of a parameterized type by using an enhanced for loop:
for (Country c : results) { System.out.println(c.getName()); }
Note: If you only need to print the country names, it is more efficient to use a projection query to retrieve only the names instead of the entire Country instances.
Single-result query execution (with getSingleResult())
You can use the getResultList()jakarta.persistence.TypedQuery.getResultList()Execute a SELECT query and return the query results as a typed List<X> . method to run queries that return a single result object. However, you must then extract the object from the result collection, for example, by using results.get(0). As a more convenient alternative for queries that are expected to return exactly one result, JPA provides the getSingleResult()jakarta.persistence.TypedQuery.getSingleResult()Execute a SELECT query that returns a single result. method.
The following aggregate query always returns a single result object, which is a Long object that represents the number of Country objects in the database:
TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries.<Long> query = em.createQueryjakarta.persistence.EntityManager.createQuery(String,Class)Create an instance of TypedQuery<X> for executing a Jakarta Persistence query language statement.( "SELECT COUNT(c) FROM Country c", Long.class); long countryCount = query.getSingleResultjakarta.persistence.TypedQuery.getSingleResult()Execute a SELECT query that returns a single result.();
When a query returns a single object of a known type, it might be tempting to use Queryjakarta.persistence.QueryInterface used to control query execution. instead of TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries. because casting a single object is straightforward:
Query query = em.createQueryjakarta.persistence.EntityManager.createQuery(String)Create an instance of Query for executing a Jakarta Persistence query language statement.("SELECT COUNT(c) FROM Country c"); long countryCount = (Long)query.getSingleResultjakarta.persistence.Query.getSingleResult()Execute a SELECT query that returns a single untyped result.();
By definition, an aggregate COUNT query always returns one result. In other cases, the expectation of a single result might be incorrect, depending on the data in the database. For example, the following query is expected to return a single Country object:
Query query = em.createQueryjakarta.persistence.EntityManager.createQuery(String)Create an instance of Query for executing a Jakarta Persistence query language statement.( "SELECT c FROM Country c WHERE c.name = 'Canada'"); Country c = (Country)query.getSingleResultjakarta.persistence.Query.getSingleResult()Execute a SELECT query that returns a single untyped result.();
However, this assumption depends on the database content. If the database contains multiple Country objects with the name 'Canada', a NonUniqueResultExceptionjakarta.persistence.NonUniqueResultExceptionThrown by the persistence provider when Query.getSingleResult or TypedQuery.getSingleResult is executed and there is more than one result from the query. is thrown. If no matching Country object is found, a NoResultExceptionjakarta.persistence.NoResultExceptionThrown by the persistence provider when Query.getSingleResult or TypedQuery.getSingleResult is executed and there is no result to return. is thrown. Therefore, use the getSingleResultjakarta.persistence.TypedQuery.getSingleResult()Execute a SELECT query that returns a single result.() method with caution and be prepared to catch and handle these exceptions.
DELETE and UPDATE query execution (with executeUpdate())
Use the executeUpdate()jakarta.persistence.Query.executeUpdate()Execute an update or delete statement. method to run DELETE and UPDATE queries.
For example, the following query deletes all Country instances:
int count = em.createQueryjakarta.persistence.EntityManager.createQuery(String)Create an instance of Query for executing a Jakarta Persistence query language statement.("DELETE FROM Country").executeUpdatejakarta.persistence.Query.executeUpdate()Execute an update or delete statement.();
The following query resets the area field in all Country instances to zero:
int count = em.createQueryjakarta.persistence.EntityManager.createQuery(String)Create an instance of Query for executing a Jakarta Persistence query language statement.("UPDATE Country SET area = 0").executeUpdatejakarta.persistence.Query.executeUpdate()Execute an update or delete statement.();
A TransactionRequiredExceptionjakarta.persistence.TransactionRequiredExceptionThrown by the persistence provider when a transaction is required but is not active. is thrown if no transaction is active.
On success, the executeUpdate() method returns the number of objects that the query updated or deleted.
The Query Structure section provides more details about DELETE and UPDATE queries.