Java Persistence/Criteria

=Criteria API= The Java Persistence Criteria API is used to define dynamic queries through the construction of object-based query definition objects, rather than use of the string-based approach of JPQL. The criteria API allows dynamic queries to be built programmatically offering better integration with the Java language than a string-based 4th GL approach.

The Criteria API has two modes, the type-restricted mode, and the non-typed mode. The type-restricted mode uses a set of JPA meta-model generated class to define the query-able attributes of a class, see Metamodel. The non-typed mode uses strings to reference attributes of a class.

The criteria API is only for dynamic queries, and cannot be used in meta-data or named queries. Criteria queries are dynamic queries, so are not as performant as static named queries, or even dynamic parametrized JPQL which may benefit from a parse cache in some JPA providers.

The Criteria API was added in JPA 2.0.

The Criteria API delete and update support was added in JPA 2.1.

CriteriaBuilder
CriteriaBuilder is the main interface into the Criteria API. A CriteriaBuilder is obtained from an EntityManager or an EntityManagerFactory using the getCriteriaBuilder API. CriteriaBuilder is used to construct CriteriaQuery objects and their expressions. The Criteria API currently only supports select queries.

CriteriaBuilder defines API to create <tt>CriteriaQuery</tt> objects:
 * <tt>createQuery</tt> - Creates a <tt>CriteriaQuery</tt>.
 * <tt>createQuery(Class)</tt> - Creates a <tt>CriteriaQuery</tt> using generics to avoid casting the result class.
 * <tt>createTupleQuery</tt> - Creates a <tt>CriteriaQuery</tt> that returns map like <tt>Tuple</tt> objects, instead of object arrays for multiselect queries. See Tuple Queries
 * <tt>createCriteriaDelete(Class)</tt> - Creates a <tt>CriteriaDelete</tt> to delete a batch of objects directly on the database (JPA 2.1).
 * <tt>createCriteriaUpdate(Class)</tt> - Creates a <tt>CriteriaUpdate</tt> to update a batch of objects directly on the database (JPA 2.1).

<tt>CriteriaBuilder</tt> also defines all supported comparison operations and functions used for defining the query's clauses.

CriteriaQuery
<tt>CriteriaQuery</tt> defines a database select query. A <tt>CriteriaQuery</tt> models all of the clauses of a JPQL select query. Elements from one <tt>CriteriaQuery</tt> cannot be used in other <tt>CriteriaQuerys</tt>. A <tt>CriteriaQuery</tt> is used with the <tt>EntityManager</tt> <tt>createQuery</tt> API to create a JPA <tt>Query</tt>.

<tt>CriteriaQuery</tt> defines the following clauses and options:
 * <tt>distinct(boolean)</tt> - Defines if the query should filter duplicate results (defaults to false). If a join to a collection relationship is used, distinct should be used to avoid duplicate results.
 * <tt>from(Class)</tt> - Defines and returns an element in the query's from clause for the entity class. At least one from element is required for the query to be valid.
 * <tt>from(EntityType)</tt> - Defines and returns an element in the query's from clause for the meta-model entity type. At least one from element is required for the query to be valid.
 * <tt>select(Selection)</tt> - Defines the query's select clause. If not set, the first root will be selected by default.
 * <tt>multiselect(Selection...)</tt>, <tt>multiselect(List<Selection>)</tt> - Defines a multi-select query.
 * <tt>where(Expression)</tt>, <tt>where(Predicate...)</tt> - Defines the query's where clause. By default all instances of the class are selected.
 * <tt>orderBy(Order...)</tt>, <tt>orderBy(List<Order>)</tt> - Defines the query's order clause. By default the results are not ordered.
 * <tt>groupBy(Expression...)</tt>, <tt>groupBy(List<Expression>)</tt> - Defines the query's group by clause. By default the results are not grouped.
 * <tt>having(Expression)</tt>, <tt>having(Predicate...)</tt> - Defines the query's having clause. Having allows grouped results to be filtered.
 * <tt>subQuery(Class)</tt> - Creates a <tt>subQuery</tt> to be used in one of the other clauses.

The <tt>Expressions</tt>, <tt>Predicates</tt>, <tt>Order</tt> elements are defined using the <tt>CriteriaBuilder</tt> API and expressions derived from the <tt>from</tt> <tt>Root</tt> elements.

Selection
A <tt>Selection</tt> defines what is selected by a query. A <tt>Selection</tt> can be any object expression, attribute expression, function, sub-select, constructor or aggregation function. An <tt>alias</tt> can be defined for a <tt>Selection</tt> using the <tt>alias</tt> API.

Aggregation functions
Aggregation functions can include summary information on a set of objects. These functions can be used to return a single result, or can be used with a <tt>groupBy</tt> to return multiple results.

Aggregate functions are defined on <tt>CriteriaBuilder</tt> and include:
 * <tt>max(Expression)</tt> - Return the maximum value for all of the results. Used for numeric types.
 * <tt>greatest(Expression)</tt> - Return the maximum value for all of the results. Used for non-numeric types.
 * <tt>min(Expression)</tt> - Return the minimum value for all of the results. Used for numeric types.
 * <tt>least(Expression)</tt> - Return the minimum value for all of the results. Used for non-numeric types.
 * <tt>avg(Expression)</tt> - Return the mean average of all of the results. A <tt>Double</tt> is returned.
 * <tt>sum(Expression)</tt> - Return the sum of all of the results.
 * <tt>sumAsLong(Expression)</tt> - Return the sum of all of the results. A <tt>Long</tt> is returned.
 * <tt>sumAsDouble(Expression)</tt> - Return the sum of all of the results. A <tt>Double</tt> is returned.
 * <tt>count(Expression)</tt> - Return the count of all of the results. <tt>null</tt> values are not counted. A <tt>Long</tt> is returned.
 * <tt>countDistinct(Expression)</tt> - Return the count of all of the distinct results. <tt>null</tt> values are not counted. A <tt>Long</tt> is returned.

Constructors
The <tt>construct</tt> operator on <tt>CriteriaBuilder</tt> can be used with a class and values to return data objects from a criteria query. These will not be managed objects, and the class must define a constructor that matches the arguments and types. Constructor queries can be used to select partial data or reporting data on objects, and get back a class instance instead of an object array or tuple.

From
The query from clause defines what is being queried. The from clause is defined using the <tt>from</tt> API on <tt>CriteriaQuery</tt>. A <tt>Root</tt> object is return from <tt>from</tt>, which represent the object in the context of the query. A <tt>Root</tt> also implements <tt>From</tt>, and <tt>Path</tt>. <tt>From</tt> defines a variable in the from clause, and allows joins. <tt>Path</tt> defines any attribute value and allows traversal to nested attributes.

Criteria queries allow for multiple root level objects. Caution should be used when doing this, as it can result in Cartesian products of the two table. The where clause should ensure the two objects are joined in some way.

Join
A <tt>join</tt> operation can be used on a <tt>From</tt> object to obtain a relationship to use in the query. <tt>join</tt> does not mean the relationships will be fetched, to also fetch the related objects in the result use the <tt>fetch</tt> operation instead.

The <tt>join</tt> operation can be used with OneToOne, ManyToOne, OneToMany, ManyToMany and ElementCollection mappings. When used with a collection relationship you can join the same relationship multiple times to query multiple independent values.

Fetch
The <tt>fetch</tt> operation can be used on a <tt>From</tt> object to fetch the related objects in a single query. This avoids additional queries for each of the object's relationships, and ensures that the relationships have been fetched if they were LAZY.

Caution should be used in using a <tt>Fetch</tt> in the where clause as it can affect the data returned for the resulting object's relationships. Objects should normally always have the same data, no matter how they were queried, this is important for caching and consistency. This is only an issue if the alias is used in the where clause on a collection relationship to filter the related objects that will be fetched. This should not be done, but is sometimes desirable, in which case the query should ensure it has been set to BYPASS the cache.

JoinType
By default <tt>join</tt> and <tt>fetch</tt> are INNER joins. This means that results that do not have the relationship will be filtered from the query results. To avoid this, a join can be defined as an OUTER join using the LEFT <tt>JoinType</tt> as an argument to the <tt>join</tt> or <tt>fetch</tt> operation.

Order
The query order by clause defines how the query results will be ordered. The order by clause is defined using the <tt>orderBy</tt> API on <tt>CriteriaQuery</tt>. Only <tt>Order</tt> objects can be passed to <tt>orderBy</tt>, and are obtained from <tt>CriteriaBuilder</tt> using the <tt>asc</tt> or <tt>desc</tt> API.

Group By
The query group by clause allows for summary information to be computed on a set of objects. group by is normally used in conjunction with aggregation functions. The group by clause is defined using the <tt>groupBy</tt> API on <tt>CriteriaQuery</tt> with any valid <tt>Expression</tt> object.

Having
The query having clause allows for the results of a group by to be filtered. The having clause is defined using the <tt>having</tt> API on <tt>CriteriaQuery</tt> with any <tt>Predicate</tt> object.

CriteriaUpdate (JPA 2.1)
<tt>CriteriaUpdate</tt> defines a database update query. A <tt>CriteriaUpdate</tt> models all of the clauses of a JPQL update query. Elements from one <tt>CriteriaUpdate</tt> cannot be used in other <tt>CriteriaUpdates</tt>. A <tt>CriteriaUpdate</tt> is used with the <tt>EntityManager</tt> <tt>createQuery</tt> API to create a JPA <tt>Query</tt>. Criteria updates should only be used for batch updates. For regular updates to objects, the objects should be read through the  in a transaction an modified in Java, and have the changes committed.

<tt>CriteriaUpdate</tt> defines the following clauses and options:
 * <tt>set(String, Object)</tt>, <tt>set(Path, Object)</tt>, <tt>set(Path, Expression)</tt> - Defines the update's set clause.
 * <tt>where(Expression)</tt>, <tt>where(Predicate...)</tt> - Defines the update's where clause. By default all instances of the class are updated.

The <tt>Expressions</tt>, <tt>Predicates</tt> elements are defined using the <tt>CriteriaBuilder</tt> API and expressions derived from the <tt>from</tt> <tt>Root</tt> elements.

CriteriaDelete (JPA 2.1)
<tt>CriteriaDelete </tt> defines a database delete query. A <tt>CriteriaDelete</tt> models all of the clauses of a JPQL delete query. Elements from one <tt>CriteriaDelete</tt> cannot be used in other <tt>CriteriaDelete</tt>. A <tt>CriteriaDelete</tt> is used with the <tt>EntityManager</tt> <tt>createQuery</tt> API to create a JPA <tt>Query</tt>. <tt>CriteriaDelete</tt> should only be used for batch deletes. For regular deletes of objects, the objects should be read through the  in a transaction and deleted through the   API, and have the changes committed.

<tt>CriteriaDelete</tt> defines the following clauses and options:
 * <tt>where(Expression)</tt>, <tt>where(Predicate...)</tt> - Defines the delete's where clause. By default all instances of the class are deleted.

The <tt>Expressions</tt>, <tt>Predicates</tt> elements are defined using the <tt>CriteriaBuilder</tt> API and expressions derived from the <tt>from</tt> <tt>Root</tt> elements.

Where
The where clause is normally the main part of the query as it defines the conditions (predicates) that filter what is returned. The where clause is defined using the <tt>where</tt> API on <tt>CriteriaQuery</tt> with any <tt>Predicate</tt> objects. A <tt>Predicate</tt> is obtained using a comparison operation, or a logical operation on <tt>CriteriaBuilder</tt>. The <tt>isNull</tt>, <tt>isNotNull</tt>, and <tt>in</tt> operations can also be called on <tt>Expression</tt>. The <tt>not</tt> operation can also be called on <tt>Predicate</tt>

SubQuery
Subqueries can only be used in the where clause and having clause. A subQuery is created from a <tt>CriteriaQuery</tt> using the <tt>subQuery</tt> operation. Most subQuery usage restricts the subQuery to returning a single result and value, unless used with the <tt>CriteriaBuilder</tt> <tt>exists</tt>, <tt>all</tt>, <tt>any</tt>, or <tt>some</tt> operations, or with an <tt>in</tt> operation.

Parameters
Parameters can be defined using the <tt>parameter</tt> API on <tt>CriteriaBuilder</tt>. JPA defines named parameters, and positional parameters. For named parameters the parameter type and name are specified. For positional parameters only the parameter type is specified. Positional parameters start at position <tt>1</tt> not <tt>0</tt>.

Functions
Several database functions are supported by the Criteria API. All supported functions are defined on <tt>CriteriaBuilder</tt>. Some functions may not be supported by some databases, if they are not SQL compliant, and offer no equivalent function.

Special Operations
The Criteria API defines several special operations that are not database functions, but have special meaning in JPA. Some of these operations are defined on <tt>CriteriaBuilder</tt> and some are on specific Expression interfaces.

Metamodel
JPA defines a meta-model that can be used at runtime to query information about the ORM mapping meta-data. The meta-model includes the list of mapped attributes for a class, and their mapping types and cardinality. The meta-model can be used with the Criteria API in place of using strings to reference the class attributes.

JPA defines a set of <tt>_</tt> classes that are to be generated by the JPA provider, or IDE, that give compile time access to the meta-model. This allows typed static variables to be used in the Criteria API. This can reduce the occurrence of typos, or invalid queries in application code, by catching query issues at compile time, instead of during testing. It does however add complexity to the development process, as the meta-model static class needs to be generated, and be part of the development cycle.

Tuple Queries
A <tt>Tuple</tt> defines a multi-select query result. Normally an object array is returned by JPA multi-select queries, but an object array is not a very useful data structure. A <tt>Tuple</tt> is a map-like structure that allows the results to be retrieved by name or index.

Tuple query examples
/Runtime