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.
This page covers the following topics:
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:
CriteriaBuilderjavax.persistence.criteria.CriteriaBuilderJPA interfaceUsed to construct criteria queries, compound selections, expressions, predicates, orderings.See JavaDoc Reference Page... cb = em.getCriteriaBuildergetCriteriaBuilder()EntityManager's methodReturn an instance of CriteriaBuilder for the creation of CriteriaQuery objects.See JavaDoc Reference Page...(); CriteriaQueryjavax.persistence.criteria.CriteriaQueryJPA interfaceThe CriteriaQuery interface defines functionality that is specific to top-level queries.See JavaDoc Reference Page...<Country> q = cb.createQuerycreateQuery(resultClass)CriteriaBuilder's methodCreate a CriteriaQuery object with the specified result type.See JavaDoc Reference Page...(Country.class); Rootjavax.persistence.criteria.RootJPA interfaceA root type in the from clause.See JavaDoc Reference Page...<Country> c = q.fromfrom(entityClass)AbstractQuery's methodCreate and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.See JavaDoc Reference Page...(Country.class); q.selectselect(selection)CriteriaQuery's methodSpecify the item that is to be returned in the query result.See JavaDoc Reference Page...(c);
The CriteriaBuilder
javax.persistence.criteria.CriteriaBuilderJPA interfaceUsed to construct criteria queries, compound selections, expressions, predicates, orderings.See JavaDoc Reference Page... interface serves as the main factory of criteria queries and criteria query elements. It can be obtained either by the EntityManagerFactory
javax.persistence.EntityManagerFactoryJPA interfaceInterface used to interact with the entity manager factory for the persistence unit.See JavaDoc Reference Page...'s getCriteriaBuilder
getCriteriaBuilder()EntityManagerFactory's methodReturn an instance of CriteriaBuilder for the creation of CriteriaQuery objects.See JavaDoc Reference Page... method or by the EntityManager
javax.persistence.EntityManagerJPA interfaceInterface used to interact with the persistence context.See JavaDoc Reference Page...'s getCriteriaBuilder
getCriteriaBuilder()EntityManager's methodReturn an instance of CriteriaBuilder for the creation of CriteriaQuery objects.See JavaDoc Reference Page... method (both methods are equivalent).
In the example above a CriteriaQuery
javax.persistence.criteria.CriteriaQueryJPA interfaceThe CriteriaQuery interface defines functionality that is specific to top-level queries.See JavaDoc Reference Page... instance is created for representing the built query. Then a Root
javax.persistence.criteria.RootJPA interfaceA root type in the from clause.See JavaDoc Reference Page... 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.
A CriteriaQuery
instance is equivalent to a JPQL string and not to a TypedQuery
javax.persistence.TypedQueryJPA interfaceInterface used to control the execution of typed queries.See JavaDoc Reference Page... instance. Therefore, running the query still requires a TypedQuery
instance:
TypedQueryjavax.persistence.TypedQueryJPA interfaceInterface used to control the execution of typed queries.See JavaDoc Reference Page...<Country> query = em.createQuerycreateQuery(criteriaQuery)EntityManager's methodCreate an instance of TypedQuery for executing a criteria query.See JavaDoc Reference Page...(q); List<Country> results = query.getResultListgetResultList()Query's methodExecute a SELECT query and return the query results as an untyped List.See JavaDoc Reference Page...();
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:
TypedQueryjavax.persistence.TypedQueryJPA interfaceInterface used to control the execution of typed queries.See JavaDoc Reference Page...<Country> query = em.createQuerycreateQuery(qlString, resultClass)EntityManager's methodCreate an instance of TypedQuery for executing a Java Persistence query language statement.See JavaDoc Reference Page...("SELECT c FROM Country c", Country.class); List<Country> results = query.getResultListgetResultList()Query's methodExecute a SELECT query and return the query results as an untyped List.See JavaDoc Reference Page...();
Because eventually both types of queries are represented by a TypedQuery
javax.persistence.TypedQueryJPA interfaceInterface used to control the execution of typed queries.See JavaDoc Reference Page... 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:
CriteriaBuilderjavax.persistence.criteria.CriteriaBuilderJPA interfaceUsed to construct criteria queries, compound selections, expressions, predicates, orderings.See JavaDoc Reference Page... cb = em.getCriteriaBuildergetCriteriaBuilder()EntityManager's methodReturn an instance of CriteriaBuilder for the creation of CriteriaQuery objects.See JavaDoc Reference Page...(); CriteriaQueryjavax.persistence.criteria.CriteriaQueryJPA interfaceThe CriteriaQuery interface defines functionality that is specific to top-level queries.See JavaDoc Reference Page...<Country> q = cb.createQuerycreateQuery(resultClass)CriteriaBuilder's methodCreate a CriteriaQuery object with the specified result type.See JavaDoc Reference Page...(Country.class); Rootjavax.persistence.criteria.RootJPA interfaceA root type in the from clause.See JavaDoc Reference Page...<Country> c = q.fromfrom(entityClass)AbstractQuery's methodCreate and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.See JavaDoc Reference Page...(Country.class); ParameterExpressionjavax.persistence.criteria.ParameterExpressionJPA interfaceType of criteria query parameter expressions.See JavaDoc Reference Page...<Integer> p = cb.parameterparameter(paramClass)CriteriaBuilder's methodCreate a parameter expression.See JavaDoc Reference Page...(Integer.class); q.selectselect(selection)CriteriaQuery's methodSpecify the item that is to be returned in the query result.See JavaDoc Reference Page...(c).wherewhere(restriction)CriteriaQuery's methodModify the query to restrict the query result according to the specified boolean expression.See JavaDoc Reference Page...(cb.gtgt(x, y)CriteriaBuilder's methodCreate a predicate for testing whether the first argument is greater than the second.See JavaDoc Reference Page...(c.getget(attributeName)Path's methodCreate a path corresponding to the referenced attribute.See JavaDoc Reference Page...("population"), p));
The ParameterExpression
javax.persistence.criteria.ParameterExpressionJPA interfaceType of criteria query parameter expressions.See JavaDoc Reference Page... instance, p
, is created to represent the query parameter. The wherewhere(restriction)CriteriaQuery's methodModify the query to restrict the query result according to the specified boolean expression.See JavaDoc Reference Page... method sets the WHERE clause. As shown above, The CriteriaQuery
javax.persistence.criteria.CriteriaQueryJPA interfaceThe CriteriaQuery interface defines functionality that is specific to top-level queries.See JavaDoc Reference Page... 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:
TypedQueryjavax.persistence.TypedQueryJPA interfaceInterface used to control the execution of typed queries.See JavaDoc Reference Page...<Country> query = em.createQuerycreateQuery(criteriaQuery)EntityManager's methodCreate an instance of TypedQuery for executing a criteria query.See JavaDoc Reference Page...(q); query.setParametersetParameter(param, value)Query's methodBind the value of a Parameter object.See JavaDoc Reference Page...(p, 10000000); List<Country> results = query.getResultListgetResultList()Query's methodExecute a SELECT query and return the query results as an untyped List.See JavaDoc Reference Page...();
The setParameter
setParameter(param, value)Query's methodBind the value of a Parameter object.See JavaDoc Reference Page... method takes a Parameter
javax.persistence.ParameterJPA interfaceType for query parameter objects.See JavaDoc Reference Page... (or a ParameterExpression
javax.persistence.criteria.ParameterExpressionJPA interfaceType of criteria query parameter expressions.See JavaDoc Reference Page...) 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:
- SELECT clause (
select
select(selection)CriteriaQuery's methodSpecify the item that is to be returned in the query result.See JavaDoc Reference Page...,distinct
distinct(distinct)CriteriaQuery's methodSpecify whether duplicate query results will be eliminated.See JavaDoc Reference Page...,multiselect
multiselect(selections)CriteriaQuery's methodSpecify the selection items that are to be returned in the query result.See JavaDoc Reference Page...,array
array(selections)CriteriaBuilder's methodCreate an array-valued selection item.See JavaDoc Reference Page...,tuple
tuple(selections)CriteriaBuilder's methodCreate a tuple-valued selection item.See JavaDoc Reference Page...,construct
construct(resultClass, selections)CriteriaBuilder's methodCreate a selection item corresponding to a constructor.See JavaDoc Reference Page...). - FROM clause (
from
from(entityClass)AbstractQuery's methodCreate and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.See JavaDoc Reference Page...,join
join(attributeName, jt)From's methodCreate a join to the specified attribute using the given join type.See JavaDoc Reference Page...,fetch
fetch(attributeName)FetchParent's methodCreate a fetch join to the specified attribute using an inner join.See JavaDoc Reference Page...). - WHERE clause (
where
where(restrictions)CriteriaQuery's methodModify the query to restrict the query result according to the conjunction of the specified restriction predicates.See JavaDoc Reference Page...). - GROUP BY / HAVING clauses (
groupBy
groupBy(grouping)CriteriaQuery's methodSpecify the expressions that are used to form groups over the query results.See JavaDoc Reference Page...,having
having(restriction)CriteriaQuery's methodSpecify a restriction over the groups of the query.See JavaDoc Reference Page...,count
count(x)CriteriaBuilder's methodCreate an aggregate expression applying the count operation.See JavaDoc Reference Page...,sum
sum(x)CriteriaBuilder's methodCreate an aggregate expression applying the sum operation.See JavaDoc Reference Page...,avg
avg(x)CriteriaBuilder's methodCreate an aggregate expression applying the avg operation.See JavaDoc Reference Page...,min
min(x)CriteriaBuilder's methodCreate an aggregate expression applying the numerical min operation.See JavaDoc Reference Page...,max
max(x)CriteriaBuilder's methodCreate an aggregate expression applying the numerical max operation.See JavaDoc Reference Page..., ...). - ORDER BY clause (
orderBy
orderBy(o)CriteriaQuery's methodSpecify the ordering expressions that are used to order the query results.See JavaDoc Reference Page...,Order
javax.persistence.criteria.OrderJPA interfaceAn object that defines an ordering over the query results.See JavaDoc Reference Page...,asc
asc(x)CriteriaBuilder's methodCreate an ordering by the ascending value of the expression.See JavaDoc Reference Page...,desc
desc(x)CriteriaBuilder's methodCreate an ordering by the descending value of the expression.See JavaDoc Reference Page...).
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:
- Literals and Dates (
literalliteral(value)CriteriaBuilder's methodCreate an expression for a literal.See JavaDoc Reference Page...
,nullLiteral
nullLiteral(resultClass)CriteriaBuilder's methodCreate an expression for a null literal with the given type.See JavaDoc Reference Page...,currentDate
currentDate()CriteriaBuilder's methodCreate expression to return current date.See JavaDoc Reference Page..., ...). - Paths, navigation and types (
getget(attributeName)Path's methodCreate a path corresponding to the referenced attribute.See JavaDoc Reference Page...
,type
type()Path's methodCreate an expression corresponding to the type of the path.See JavaDoc Reference Page...). - Arithmetic expressions (
sum
sum(x, y)CriteriaBuilder's methodCreate an expression that returns the sum of its arguments.See JavaDoc Reference Page...,diff
diff(x, y)CriteriaBuilder's methodCreate an expression that returns the difference between its arguments.See JavaDoc Reference Page...,prod
prod(x, y)CriteriaBuilder's methodCreate an expression that returns the product of its arguments.See JavaDoc Reference Page...,quot
quot(x, y)CriteriaBuilder's methodCreate an expression that returns the quotient of its arguments.See JavaDoc Reference Page...,mod
mod(x, y)CriteriaBuilder's methodCreate an expression that returns the modulus of its arguments.See JavaDoc Reference Page...,abs
abs(x)CriteriaBuilder's methodCreate an expression that returns the absolute value of its argument.See JavaDoc Reference Page...,neg
neg(x)CriteriaBuilder's methodCreate an expression that returns the arithmetic negation of its argument.See JavaDoc Reference Page...,sqrt
sqrt(x)CriteriaBuilder's methodCreate an expression that returns the square root of its argument.See JavaDoc Reference Page...). - String expressions (
like
like(x, pattern)CriteriaBuilder's methodCreate a predicate for testing whether the expression satisfies the given pattern.See JavaDoc Reference Page...,length
length(x)CriteriaBuilder's methodCreate expression to return length of a string.See JavaDoc Reference Page...,locate
locate(x, pattern)CriteriaBuilder's methodCreate expression to locate the position of one string within another, returning position of first character if found.See JavaDoc Reference Page...,lower
lower(x)CriteriaBuilder's methodCreate expression for converting a string to lowercase.See JavaDoc Reference Page...,upper
upper(x)CriteriaBuilder's methodCreate expression for converting a string to uppercase.See JavaDoc Reference Page...,concat
concat(x, y)CriteriaBuilder's methodCreate an expression for string concatenation.See JavaDoc Reference Page...,substringsubstring(x, from)CriteriaBuilder's methodCreate an expression for substring extraction.See JavaDoc Reference Page..., ...
). - Collection expressions (
isEmpty
isEmpty(collection)CriteriaBuilder's methodCreate a predicate that tests whether a collection is empty.See JavaDoc Reference Page...,isNotEmpty
isNotEmpty(collection)CriteriaBuilder's methodCreate a predicate that tests whether a collection is not empty.See JavaDoc Reference Page...,isMember
isMember(elem, collection)CriteriaBuilder's methodCreate a predicate that tests whether an element is a member of a collection.See JavaDoc Reference Page...,isNotMember
isNotMember(elem, collection)CriteriaBuilder's methodCreate a predicate that tests whether an element is not a member of a collection.See JavaDoc Reference Page...,size
size(collection)CriteriaBuilder's methodCreate an expression that tests the size of a collection.See JavaDoc Reference Page...). - Comparison expressions (
equal
size(collection)CriteriaBuilder's methodCreate an expression that tests the size of a collection.See JavaDoc Reference Page...,notEqual
notEqual(x, y)CriteriaBuilder's methodCreate a predicate for testing the arguments for inequality.See JavaDoc Reference Page...,gt
gt(x, y)CriteriaBuilder's methodCreate a predicate for testing whether the first argument is greater than the second.See JavaDoc Reference Page...,ge
ge(x, y)CriteriaBuilder's methodCreate a predicate for testing whether the first argument is greater than or equal to the second.See JavaDoc Reference Page...,lt
lt(x, y)CriteriaBuilder's methodCreate a predicate for testing whether the first argument is less than the second.See JavaDoc Reference Page...,le
le(x, y)CriteriaBuilder's methodCreate a predicate for testing whether the first argument is less than or equal to the second.See JavaDoc Reference Page...,between
between(v, x, y)CriteriaBuilder's methodCreate a predicate for testing whether the first argument is between the second and third arguments in value.See JavaDoc Reference Page...,isNull
isNull(x)CriteriaBuilder's methodCreate a predicate to test whether the expression is null.See JavaDoc Reference Page..., ...) - Logical expressions (
and
and(x, y)CriteriaBuilder's methodCreate a conjunction of the given boolean expressions.See JavaDoc Reference Page...,or
or(x, y)CriteriaBuilder's methodCreate a disjunction of the given boolean expressions.See JavaDoc Reference Page...,not
not(restriction)CriteriaBuilder's methodCreate a negation of the given restriction.See JavaDoc Reference Page...,isTrue
isTrue(x)CriteriaBuilder's methodCreate a predicate testing for a true value.See JavaDoc Reference Page...).
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.