The Java EE 6 Tutorial, Volume I

Executing Queries

To prepare a query for execution, create a TypedQuery<T> object with the type of the query result by passing the CriteriaQuery object to EntityManager.createQuery.

Queries are executed by calling either getSingleResult or getResultList on the TypedQuery<T> object.

Single-Valued Query Results

The TypedQuery<T>.getSingleResult method is used for executing queries that return a single result.


Example 22–25 Retrieving Single-Valued Query Result

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
...
TypedQuery<Pet> q = em.createQuery(cq);
Pet result = q.getSingleResult();

Collection-Valued Query Results

The TypedQuery<T>.getResultList method is used for executing queries that return a collection of objects.


Example 22–26 Retrieving Collection-Valued Query Results

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
...
TypedQuery<Pet> q = em.createQuery(cq);
List<Pet> results = q.getResultList();