The Java EE 6 Tutorial, Volume I

Query Roots

For a particular CriteriaQueryobject, the root entity of the query, from which all navigation originates, is called the query root. It is similar to the FROM clause in a JPQL query.

Create the query root by calling the from method on the CriteriaQuery instance. The argument to the from method is either the entity class, or an EntityType<T> instance for the entity.

Example 22–7 Setting the Query Root Using the Entity Class

The following code sets the query root to the Pet entity.

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

Example 22–8 Setting the Query Root Using a Metamodel EntityType<T> Instance

The following code sets the query root to the Pet class using an EntityType<T> instance.

EntityManager em = ...;
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
Root<Pet> pet = cq.from(Pet_);

Criteria queries may have more than one query root. This usually occurs when the query navigates from several entities.

Example 22–9 Creating a Query with Multiple Query Roots

The following code has two Root instances.

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet1 = cq.from(Pet.class);
Root<Pet> pet2 = cq.from(Pet.class);