JPA Criteria API Queries

The JPA Criteria API provides an alternative way for defining JPA queries, which is mainly useful for building dynamic queries whose exact structure is only known at runtime.

JPA Criteria API vs JPQL

JPQL queries are defined as strings, similarly to SQL. JPA criteria queries, on the other hand, are defined by the instantiation of Java objects that represent query elements.

A major advantage of using the criteria API is that errors can be detected earlier, during compilation rather than at runtime. On the other hand, for many developers string based JPQL queries, which are very similar to SQL queries, are easier to use and understand.

For simple static queries - string based JPQL queries (e.g. as named queries) may be preferred. For dynamic queries that are built at runtime - the criteria API may be preferred.

For example, building a dynamic query based on fields that a user fills at runtime in a form that contains many optional fields - is expected to be cleaner when using the JPA criteria API, because it eliminates the need for building the query using many string concatenation operations.

String based JPQL queries and JPA criteria based queries are equally powerful and efficient. Therefore, choosing one method over the other is also a matter of personal preference. 

First JPA Criteria Query

The following query string represents a minimal JPQL query:

SELECT c FROM Country c

An equivalent query can be built using the JPA criteria API as follows:

  CriteriaBuilderjakarta.persistence.criteria.CriteriaBuilder - JPA Interface
 Used to construct criteria queries, compound selections,
 expressions, predicates, orderings. cb = em.getCriteriaBuilderEntityManager.getCriteriaBuilder() - JPA Method
 Obtain an instance of CriteriaBuilder which may be
 used to construct CriteriaQuery objects.();

  CriteriaQueryjakarta.persistence.criteria.CriteriaQuery - JPA Interface
 The {@code CriteriaQuery} interface defines functionality that is
 specific to top-level queries.<Country> q = cb.createQueryCriteriaBuilder.createQuery(resultClass) - JPA Method
 Create a CriteriaQuery object with the given
 result type.(Country.class);
  Rootjakarta.persistence.criteria.Root - JPA Interface
 A root type in the from clause.<Country> c = q.fromAbstractQuery.from(entityClass) - JPA Method
 Create and add a query root corresponding to the given entity,
 forming a cartesian product with any existing roots.(Country.class);
  q.selectCriteriaQuery.select(selection) - JPA Method
 Specify the item that is to be returned in the query result.(c);

The CriteriaBuilderjakarta.persistence.criteria.CriteriaBuilder - JPA Interface Used to construct criteria queries, compound selections, expressions, predicates, orderings. interface serves as the main factory of criteria queries and criteria query elements. It can be obtained either by the EntityManagerFactoryjakarta.persistence.EntityManagerFactory - JPA Interface Interface used to interact with the persistence unit, and to create new instances of EntityManager.'s getCriteriaBuilderEntityManagerFactory.getCriteriaBuilder() - JPA Method Return an instance of CriteriaBuilder which may be used to construct jakarta.persistence.criteria.CriteriaQuery objects. method or by the EntityManagerjakarta.persistence.EntityManager - JPA Interface Interface used to interact with the persistence context.'s getCriteriaBuilderEntityManager.getCriteriaBuilder() - JPA Method Obtain an instance of CriteriaBuilder which may be used to construct CriteriaQuery objects. method (both methods are equivalent).

In the example above a CriteriaQueryjakarta.persistence.criteria.CriteriaQuery - JPA Interface The {@code CriteriaQuery} interface defines functionality that is specific to top-level queries. instance is created for representing the built query. Then a Rootjakarta.persistence.criteria.Root - JPA Interface A root type in the from clause. instance is created to define a range variable in the FROM clause. Finally, the range variable, c, is also used in the SELECT clause as the query result expression. CriteriaQueryTypedQueryjakarta.persistence.TypedQuery - JPA Interface Interface used to control the execution of typed queries.TypedQuery

  TypedQueryjakarta.persistence.TypedQuery - JPA Interface
 Interface used to control the execution of typed queries.<Country> query = em.createQueryEntityManager.createQuery(criteriaQuery) - JPA Method
 Create an instance of TypedQuery for executing a
 criteria query.(q);
  List<Country> results = query.getResultListQuery.getResultList() - JPA Method
 Execute a SELECT query and return the query results as an untyped
 List.();

Using the criteria API introduces some extra work, at least for simple static queries, since the equivalent JPQL query could simply be executed as follows:

  TypedQueryjakarta.persistence.TypedQuery - JPA Interface
 Interface used to control the execution of typed queries.<Country> query =
      em.createQueryEntityManager.createQuery(qlString,resultClass) - JPA Method
 Create an instance of TypedQuery for executing a
 Jakarta Persistence query language statement.("SELECT c FROM Country c", Country.class);
  List<Country> results = query.getResultListQuery.getResultList() - JPA Method
 Execute a SELECT query and return the query results as an untyped
 List.();

Because eventually both types of queries are represented by a TypedQueryjakarta.persistence.TypedQuery - JPA Interface Interface used to control the execution of typed queries. instance - query execution and query setting is similar, regardless of the way in which the query is built.

Parameters in Criteria Queries

The following query string represents a JPQL query with a parameter:

SELECT c FROM Country c WHERE c.population > :p

An equivalent query can be built using the JPA criteria API as follows:

  CriteriaBuilderjakarta.persistence.criteria.CriteriaBuilder - JPA Interface
 Used to construct criteria queries, compound selections,
 expressions, predicates, orderings. cb = em.getCriteriaBuilderEntityManager.getCriteriaBuilder() - JPA Method
 Obtain an instance of CriteriaBuilder which may be
 used to construct CriteriaQuery objects.();

  CriteriaQueryjakarta.persistence.criteria.CriteriaQuery - JPA Interface
 The {@code CriteriaQuery} interface defines functionality that is
 specific to top-level queries.<Country> q = cb.createQueryCriteriaBuilder.createQuery(resultClass) - JPA Method
 Create a CriteriaQuery object with the given
 result type.(Country.class);
  Rootjakarta.persistence.criteria.Root - JPA Interface
 A root type in the from clause.<Country> c = q.fromAbstractQuery.from(entityClass) - JPA Method
 Create and add a query root corresponding to the given entity,
 forming a cartesian product with any existing roots.(Country.class);
  ParameterExpressionjakarta.persistence.criteria.ParameterExpression - JPA Interface
 Type of criteria query parameter expressions.<Integer> p = cb.parameterCriteriaBuilder.parameter(paramClass) - JPA Method
 Create a parameter expression.(Integer.class);
  q.selectCriteriaQuery.select(selection) - JPA Method
 Specify the item that is to be returned in the query result.(c).whereCriteriaQuery.where(restriction) - JPA Method
 Modify the query to restrict the query result according
 to the specified boolean expression.(cb.gtCriteriaBuilder.gt(x,y) - JPA Method
 Create a predicate for testing whether the first argument is
 greater than the second.(c.getPath.get(attributeName) - JPA Method
 Create a path corresponding to the referenced attribute.("population"), p));

The ParameterExpressionjakarta.persistence.criteria.ParameterExpression - JPA Interface Type of criteria query parameter expressions. instance, p, is created to represent the query parameter. The whereCriteriaQuery.where(restriction) - JPA Method Modify the query to restrict the query result according to the specified boolean expression. method sets the WHERE clause. As shown above, The CriteriaQueryjakarta.persistence.criteria.CriteriaQuery - JPA Interface The {@code CriteriaQuery} interface defines functionality that is specific to top-level queries. interface supports method chaining. See the links in the next sections of this page for detailed explanations on how to set criteria query clauses and build criteria expressions.

Running this query requires setting the parameter:

  TypedQueryjakarta.persistence.TypedQuery - JPA Interface
 Interface used to control the execution of typed queries.<Country> query = em.createQueryEntityManager.createQuery(criteriaQuery) - JPA Method
 Create an instance of TypedQuery for executing a
 criteria query.(q);
  query.setParameterQuery.setParameter(param,value) - JPA Method
 Bind the value of a {@code Parameter} object.(p, 10000000);
  List<Country> results = query.getResultListQuery.getResultList() - JPA Method
 Execute a SELECT query and return the query results as an untyped
 List.();

The setParameterQuery.setParameter(param,value) - JPA Method Bind the value of a {@code Parameter} object. method takes a Parameterjakarta.persistence.Parameter - JPA Interface Type for query parameter objects. (or a ParameterExpressionjakarta.persistence.criteria.ParameterExpression - JPA Interface Type of criteria query parameter expressions.) instance as the first argument instead of a name or a position (which are used with string based JPQL parameters).

Criteria Query Structure

Queries in JPA (as in SQL) are composed of clauses. Because JPQL queries and criteria queries use equivalent clauses - they are explained side by side in the Query Structure pages.

Specific details about criteria query clauses are provided in the following page sections:

The links above are direct links to the criteria query sections in pages that describe query structure in general, including in the context of string based JPQL queries.

Criteria Query Expressions

JPA query clauses are composed of expressions. Because JPQL queries and criteria queries use equivalent expressions - they are explained side by side in the Query Expressions pages.

Specific details about criteria query expressions are provided in the following page sections:

The links above are direct links to the criteria query sections in pages that describe expressions in general, including in the context of string based JPQL queries.