The Java EE 7 Tutorial
Similar to JPQL, the Criteria API is based on the abstract schema of persistent entities, their relationships, and embedded objects. The Criteria API operates on this abstract schema to allow developers to find, modify, and delete persistent entities by invoking Java Persistence API entity operations. The Metamodel API works in concert with the Criteria API to model persistent entity classes for Criteria queries.
The Criteria API and JPQL are closely related and are designed to allow similar operations in their queries. Developers familiar with JPQL syntax will find equivalent object-level operations in the Criteria API.
The following simple Criteria query returns all instances of the
Pet entity in the data source:
EntityManager em = ...; CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.select(pet); TypedQuery<Pet> q = em.createQuery(cq); List<Pet> allPets = q.getResultList();
The equivalent JPQL query is
SELECT p FROM Pet p
This query demonstrates the basic steps to create a Criteria query.
EntityManagerinstance to create a
Create a query object by creating an instance of the
CriteriaQueryinterface. This query object's attributes will be modified with the details of the query.
Set the query root by calling the
frommethod on the
Specify what the type of the query result will be by calling the
selectmethod of the
Prepare the query for execution by creating a
TypedQuery<T>instance, specifying the type of the query result.
Execute the query by calling the
getResultListmethod on the
TypedQuery<T>object. Because this query returns a collection of entities, the result is stored in a
The tasks associated with each step are discussed in detail in this chapter.
To create a
CriteriaBuilder instance, call the
getCriteriaBuilder method on the
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaBuilder instance to create a query object:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
The query will return instances of the
Pet entity. To create a typesafe query, specify the type of the query when you create the
from method of the query object to set the
FROM clause of the query and to specify the root of the query:
Root<Pet> pet = cq.from(Pet.class);
select method of the query object, passing in the query root, to set the
SELECT clause of the query:
Now, use the query object to create a
TypedQuery<T> object that can be executed against the data source. The modifications to the query object are captured to create a ready-to-execute query:
TypedQuery<Pet> q = em.createQuery(cq);
Execute this typed query object by calling its
getResultList method, because this query will return multiple entity instances. The following statement stores the results in a
List<Pet> collection-valued object:
List<Pet> allPets = q.getResultList();