The Java EE 6 Tutorial, Volume I

Overview of the Criteria and Metamodel APIs

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 designed to allow similar operations in their queries. Developers familiar with JPQL syntax will find equivalent object-level operations in the Criteria API.


Example 22–1 A Simple Criteria Query

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);
TypeQuery<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:

The tasks associated with each step are discussed in detail in this chapter.

To create a CriteriaBuilder instance call the getCriteriaBuilder method on the EntityManager instance:

CriteriaBuilder cb = em.getCriteriaBuilder();

The actual query object is created using the CriteriaBuilder instance:

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);

The query will return instances of the Pet entity, so the type of the query is specified when the CriteriaQuery object is created to create a type-safe query.

The from clause of the query is set, and the root of the query specified, by calling the from method of the query object:

Root<Pet> pet = cq.from(Pet.class);

The select clause of the query is set by calling the select method of the query object, and passing in the query root:

cq.select(pet);

The query object is now used 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.

TypeQuery<Pet> q = em.createQuery(cq);

This typed query object is executed by calling its getResultList method, because this query will return multiple entity instances. The results are stored in a List<Pet> collection-valued object.

List<Pet> allPets = q.getResultList();