The Java EE 6 Tutorial, Volume I

Creating a Criteria Query

The javax.persistence.criteria.CriteriaBuilder interface is used to construct:

To obtain an instance of the CriteriaBuilder interface, call the getCriteriaBuilder method on either an EntityManager or EntityManagerFactory instance.

Example 22–5 Obtaining a CriteriaBuilder Instance Using the EntityManager.getCriteriaManager Method

The following code shows how to obtain a CriteriaBuilder instance using the EntityManager.getCriteriaBuilder method.

EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();

Criteria queries are constructed by obtaining an instance of the javax.persistence.criteria.CriteriaQuery interface. CriteriaQuery objects define a particular query that will navigate over one or more entities. Obtain CriteriaQuery instances by calling one of the CrtieriaBuilder.createQuery methods. For creating type-safe queries, call the CriteriaBuilder.createQuery method as follows:

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

The CriteriaQuery object's type should be set to the expected result type of the query. In the code above, the object's type is set to CriteriaQuery<Pet> for a query which will find instances of the Pet entity.

Example 22–6 Creating a CriteriaQuery Instance for a Query that Returns a String

In the following code snippet, a CriteriaQuery object is created for a query that returns a string.

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