JPA Criteria API Queries

The JPA Criteria API provides an alternative way to define JPA queries. It is useful for building dynamic queries whose structure is known only at runtime.

JPA Criteria API vs. JPQL

JPQL queries are defined as strings, similar to SQL. In contrast, JPA Criteria queries are defined by instantiating Java objects that represent query elements.

A major advantage of the Criteria API is that it enables compile-time error checking. Errors in string-based JPQL queries, however, are found at runtime. Many developers find string-based JPQL queries easier to use and understand because of their similarity to SQL.

String-based JPQL queries, such as named queries, are often preferred for simple, static queries. The Criteria API is generally better for dynamic queries that are built at runtime.

For example, building a dynamic query based on a form with many optional fields is cleaner with the Criteria API because it avoids complex string concatenation.

String-based JPQL queries and JPA Criteria-based queries are equally powerful and efficient. Therefore, the choice between them can also be a matter of personal preference.

First JPA Criteria query

The following string is a minimal JPQL query:

SELECT c FROM Country c

You can build an equivalent query with the JPA Criteria API as follows:

  CriteriaBuilderjakarta.persistence.criteria.CriteriaBuilderUsed to construct criteria queries, compound selections, expressions, predicates, orderings. cb = em.getCriteriaBuilderjakarta.persistence.EntityManager.getCriteriaBuilder()Obtain an instance of   CriteriaBuilder   which may be used to construct   CriteriaQuery<T>   objects.();
  CriteriaQueryjakarta.persistence.criteria.CriteriaQueryThe  CriteriaQuery  interface defines functionality that is specific to top-level queries.<Country> q = cb.createQueryjakarta.persistence.criteria.CriteriaBuilder.createQuery(Class)Create a   CriteriaQuery<T>   object with the given result type.(Country.class);
  Rootjakarta.persistence.criteria.RootA root type in the from clause.<Country> c = q.fromjakarta.persistence.criteria.AbstractQuery.from(Class)Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.(Country.class);
  q.selectjakarta.persistence.criteria.CriteriaQuery.select(Selection)Specify the item that is to be returned in the query result.(c);

The CriteriaBuilderjakarta.persistence.criteria.CriteriaBuilderUsed to construct criteria queries, compound selections, expressions, predicates, orderings. interface is the main factory for Criteria queries and their elements. You can get an instance from either the EntityManagerFactoryjakarta.persistence.EntityManagerFactoryInterface used to interact with the persistence unit, and to create new instances of EntityManager .'s getCriteriaBuilderjakarta.persistence.EntityManagerFactory.getCriteriaBuilder()Return an instance of CriteriaBuilder which may be used to construct CriteriaQuery<T> objects. method or the EntityManagerjakarta.persistence.EntityManagerInterface used to interact with the persistence context.'s getCriteriaBuilderjakarta.persistence.EntityManager.getCriteriaBuilder()Obtain an instance of CriteriaBuilder which may be used to construct CriteriaQuery<T> objects. method.

In the example, a CriteriaQueryjakarta.persistence.criteria.CriteriaQueryThe CriteriaQuery interface defines functionality that is specific to top-level queries. instance is created to represent the query. A Rootjakarta.persistence.criteria.RootA root type in the from clause. instance defines the FROM clause's range variable. Finally, the range variable, c, is used in the SELECT clause as the query's result expression.

After building the CriteriaQuery, you use it to create a TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries. object, which you can then execute:

  TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries.<Country> query = em.createQueryjakarta.persistence.EntityManager.createQuery(CriteriaQuery)Create an instance of   TypedQuery<X>   for executing a criteria query.(q);
  List<Country> results = query.getResultListjakarta.persistence.Query.getResultList()Execute a SELECT query and return the query results as an untyped   List<E>  .();

The Criteria API requires more code, especially for simple static queries. The equivalent JPQL query can be executed more concisely:

  TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries.<Country> query =
      em.createQueryjakarta.persistence.EntityManager.createQuery(String,Class)Create an instance of   TypedQuery<X>   for executing a Jakarta Persistence query language statement.("SELECT c FROM Country c", Country.class);
  List<Country> results = query.getResultListjakarta.persistence.Query.getResultList()Execute a SELECT query and return the query results as an untyped   List<E>  .();

Because both types of queries are ultimately represented by a TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries. instance, query execution and settings are similar, regardless of how the query is built.

Parameters in Criteria queries

The following string is a JPQL query with a parameter:

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

You can build an equivalent query with the JPA Criteria API as follows:

  CriteriaBuilderjakarta.persistence.criteria.CriteriaBuilderUsed to construct criteria queries, compound selections, expressions, predicates, orderings. cb = em.getCriteriaBuilderjakarta.persistence.EntityManager.getCriteriaBuilder()Obtain an instance of   CriteriaBuilder   which may be used to construct   CriteriaQuery<T>   objects.();
  CriteriaQueryjakarta.persistence.criteria.CriteriaQueryThe  CriteriaQuery  interface defines functionality that is specific to top-level queries.<Country> q = cb.createQueryjakarta.persistence.criteria.CriteriaBuilder.createQuery(Class)Create a   CriteriaQuery<T>   object with the given result type.(Country.class);
  Rootjakarta.persistence.criteria.RootA root type in the from clause.<Country> c = q.fromjakarta.persistence.criteria.AbstractQuery.from(Class)Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.(Country.class);
  ParameterExpressionjakarta.persistence.criteria.ParameterExpressionType of criteria query parameter expressions.<Integer> p = cb.parameterjakarta.persistence.criteria.CriteriaBuilder.parameter(Class)Create a parameter expression.(Integer.class);
  q.selectjakarta.persistence.criteria.CriteriaQuery.select(Selection)Specify the item that is to be returned in the query result.(c).wherejakarta.persistence.criteria.CriteriaQuery.where(Expression)Modify the query to restrict the query result according to the specified boolean expression.(cb.gtjakarta.persistence.criteria.CriteriaBuilder.gt(Expression,Expression)Create a predicate for testing whether the first argument is greater than the second.(c.getjakarta.persistence.criteria.Path.get(String)Create a path corresponding to the referenced attribute.("population"), p));

The p ParameterExpressionjakarta.persistence.criteria.ParameterExpressionType of criteria query parameter expressions. instance represents the query parameter. The wherejakarta.persistence.criteria.CriteriaQuery.where(Expression)Modify the query to restrict the query result according to the specified boolean expression. method sets the WHERE clause. As shown, the CriteriaQueryjakarta.persistence.criteria.CriteriaQueryThe CriteriaQuery interface defines functionality that is specific to top-level queries. interface supports method chaining. For details on setting clauses and building expressions, see the links in the following sections.

To run this query, you must set the parameter value:

  TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries.<Country> query = em.createQueryjakarta.persistence.EntityManager.createQuery(CriteriaQuery)Create an instance of   TypedQuery<X>   for executing a criteria query.(q);
  query.setParameterjakarta.persistence.Query.setParameter(Parameter,T)Bind the value of a  Parameter  object.(p, 10000000);
  List<Country> results = query.getResultListjakarta.persistence.Query.getResultList()Execute a SELECT query and return the query results as an untyped   List<E>  .();

The setParameterjakarta.persistence.Query.setParameter(Parameter,T)Bind the value of a Parameter object. method takes a Parameterjakarta.persistence.ParameterType for query parameter objects. instance (such as a ParameterExpressionjakarta.persistence.criteria.ParameterExpressionType of criteria query parameter expressions.) as its first argument. This differs from string-based JPQL parameters, which use a name or position.

Criteria query structure

JPA queries, like SQL queries, consist of clauses. Because JPQL and Criteria queries use equivalent clauses, this guide explains them side-by-side in the Query Structure pages.

The following sections provide specific details about Criteria query clauses:

The links above go to the Criteria query sections within pages that also cover string-based JPQL queries.

Criteria query expressions

JPA query clauses consist of expressions. Because JPQL and Criteria queries use equivalent expressions, this guide explains them side-by-side in the Query Expressions pages.

The following sections provide specific details about Criteria query expressions:

The links above go to the Criteria query sections within pages that also cover string-based JPQL queries.