The Java EE 6 Tutorial

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 an EntityManagerFactory instance.

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

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

Criteria queries are constructed by obtaining an instance of the following interface:

javax.persistence.criteria.CriteriaQuery

CriteriaQuery objects define a particular query that will navigate over one or more entities. Obtain CriteriaQuery instances by calling one of the CriteriaBuilder.createQuery methods. For creating typesafe 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 preceding code, the object’s type is set to CriteriaQuery<Pet> for a query that will find instances of the Pet entity.

In the following code snippet, a CriteriaQuery object is created for a query that returns a String:

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