You are on page 1of 7

06/10/2018 EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Criteria - Eclipsepedia

1 Cookie
Criteria API
settings
1.1 CriteriaBuilder
1.2 CriteriaQuery
1.2.1 CriteriaQuery examples
1.2.2 Selection
1.2.2.1 Aggregation functions
1.2.2.2 Constructors
1.2.3 From
1.2.3.1 Join
1.2.3.2 Fetch
1.2.3.3 JoinType
1.2.4 Order
1.2.5 Group By
1.2.6 Having
1.3 Where
1.4 Subquery
1.4.1 Subquery examples
1.5 Parameters
1.5.1 Named parameter criteria example
1.5.2 Positional parameter criteria example
1.6 Functions
1.7 Special Operations
1.8 Metamodel
1.8.1 Metamodel criteria example
1.9 Tuple Queries
1.9.1 Tuple query examples
1.10 JpaCriteriaBuilder and EclipseLink Extensions
1.10.1 JpaCriteriaBuilder native Expression example

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 programatically 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 benefit from EclipseLink's parse cache.
The Criteria API was added in JPA 2.0, and EclipseLink 2.0.
For more information, see Chapter 6 "Criteria API" in the JPA Specification (http://jcp.org/en/jsr/detail?id=317).
(http://jcp.org/en/jsr/detail?
id=317)
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 CriteriaQuery objects:

createQuery() - Creates a CriteriaQuery.


createQuery(Class) - Creates a CriteriaQuery using generics to avoid casting the result class.
createTupleQuery() - Creates a CriteriaQuery that returns map like Tuple objects, instead of object arrays for multiselect queries. See Tuple
Queries
CriteriaBuilder also defines all supported comparison operations and functions used for defining the query's clauses.

CriteriaQuery
CriteriaQuery defines a database select query. A CriteriaQuery models all of the clauses of a JPQL select query. Elements from one CriteriaQuery
cannot be used in other CriteriaQuerys. A CriteriaQuery is used with the EntityManager createQuery() API to create a JPA Query.
CriteriaQuery defines the following clauses and options:

distinct(boolean) - 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.
from(Class) - 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.
from(EntityType) - 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.
select(Selection) - Defines the query's select clause. If not set, the first root will be selected by default.
multiselect(Selection...), multiselect(List<Selection>) - Defines a multi-select query.
where(Expression), where(Predicate...) - Defines the query's where clause. By default all instances of the class are selected.
orderBy(Order...), orderBy(List<Order>) - Defines the query's order clause. By default the results are not ordered.
groupBy(Expression...), groupBy(List<Expression>) - Defines the query's group by clause. By default the results are not grouped.
having(Expression), having(Predicate...) - Defines the query's having clause. Having allows grouped results to be filtered.
subquery(Class) - Creates a Subquery to be used in one of the other clauses.

The Expressions, Predicates, Order elements are defined using the CriteriaBuilder API and expressions derived from the from Root elements.
CriteriaQuery examples

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria 2/8
06/10/2018 EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Criteria - Eclipsepedia
Cookie settings
CriteriaBuilder cb = em.getCriteriaBuilder();
 
// Query for a List of objects.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.where(cb.greaterThan(e.get("salary"), 100000));
Query query = em.createQuery(cq);
List<Employee> result = query.getResultList();
 
// Query for a single object.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.where(cb.equal(e.get("id"), cb.parameter(Long.class, "id")));
Query query = em.createQuery(cq);
query.setParameter("id", id);
Employee result2 = (Employee)query.getSingleResult();
 
// Query for a single data element.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.select(cb.max(e.get("salary")));
Query query = em.createQuery(cq);
BigDecimal result3 = (BigDecimal)query.getSingleResult();
 
// Query for a List of data elements.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.select(e.get("firstName"));
Query query = em.createQuery(cq);
List<String> result4 = query.getResultList();
 
// Query for a List of element arrays.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.multiselect(e.get("firstName"), employee.get("lastName"));
Query query = em.createQuery(cq);
List<Object[]> result5 = query.getResultList();

Selection
A Selection define what is selected by a query. A Selection can be any object expression, attribute expression, function, sub-select, constructor or aggregation
function. An alias can be defined for a Selection using the alias() 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 groupBy to
return multiple results.
Aggregate functions are defined on CriteriaBuilder and include:

max(Expression) - Return the maximum value for all of the results. Used for numeric types.
greatest(Expression) - Return the maximum value for all of the results. Used for non-numeric types.
min(Expression) - Return the minimum value for all of the results. Used for numeric types.
least(Expression) - Return the minimum value for all of the results. Used for non-numeric types.
avg(Expression) - Return the mean average of all of the results. A Double is returned.
sum(Expression) - Return the sum of all of the results.
sumAsLong(Expression) - Return the sum of all of the results. A Long is returned.
sumAsDouble(Expression) - Return the sum of all of the results. A Double is returned.
count(Expression) - Return the count of all of the results. null values are not counted. A Long is returned.
countDistinct(Expression) - Return the count of all of the distinct results. null values are not counted. A Long is returned.

CriteriaBuilder cb = em.getCriteriaBuilder();
 
// Count the total employees
CriteriaQuery cq = cb.createQuery();
Root employee = cq.from(Employee.class);
cq.select(cb.count(employee));
Query query = em.createQuery(cq);
List<Employee> result = query.getResultList();
 
// Maximum salary
CriteriaQuery cq = cb.createQuery();
Root employee = cq.from(Employee.class);
cq.select(cb.max(employee.get("salary"));
Query query = em.createQuery(cq);
List<Employee> result = query.getResultList();

Constructors
The construct operator on CriteriaBuilder 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.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.select(cb.construct(EmpReport.class, e.get("firstName"), e.get("lastName"), e.get("salary")));
Query query = em.createQuery(cq);
List<EmpReport> result = query.getResultList();

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

Root e = cq.from(Employee.class);

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.

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria 3/8
06/10/2018 EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Criteria - Eclipsepedia
Cookie
// Select thesettings
employees and the mailing addresses that have the same address.
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
Root a = cq.from(MailingAddress.class);
cq.multiselect(e, a);
cq.where(cb.equal(e.get("address"), a.get("address"));
Query query = em.createQuery(cq);
List<Object[]> result = query.getResultList();

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

Root e = cq.from(Employee.class);
Join a = e.join("address");
cq.where(cb.equal(a.get("city"), city);

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

// All employees who work on both projects.


Root e = cq.from(Employee.class);
Join p = e.join("projects");
Join p2 = e.join("projects");
cq.where(cb.and(cb.equal(p.get("name"), p1), cb.equal(p2.get("name"), p2));

Fetch
The fetch operation can be used on a From 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. EclipseLink also supports batch fetching through query hints.

Root e = cq.from(Employee.class);
Fetch a = e.fetch("address");
cq.select(e);

Caution should be used in using a Fetch 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 join and fetch 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 JoinType as an argument to the join or fetch operation.

Root e = cq.from(Employee.class);
Join a = e.join("address", JoinType.LEFT);
cq.order(a.get("city"));

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

// Order by the last and first names.


Root e = cq.from(Employee.class);
cq.orderBy(cb.desc(e.get("lastName")), cb.asc(e.get("firstName")));

// Order by the last name, ignoring case.


Root e = cq.from(Employee.class);
cq.orderBy(cb.asc(cb.upper(e.get("lastName"))));

// Order by the address object (orders by its id).


Root e = cq.from(Employee.class);
cq.orderBy(cb.asc(e.get("address")));

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 groupBy API on CriteriaQuery with any valid Expression object.

// Select the average salaries grouped by city.


Root e = cq.from(Employee.class);
cq.multiselect(cb.avg(e.<Number>get("salary")), e.get("address").get("city"));
cq.groupBy(e.get("address").get("city"));

// Select the average salaries grouped by city, ordered by the average salary.
Root e = cq.from(Employee.class);
Expression avg = cb.avg(e.<Number>get("salary"));
cq.multiselect(avg, e.get("address").get("city"));
cq.groupBy(e.get("address").get("city"));
cq.orderBy(avg);

// Select employees and the count of their number of projects.


Root e = cq.from(Employee.class);
Expression p = e.join("projects", JoinType.LEFT);
cq.multiselect(e, cb.count(p));
cq.groupBy(e);

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

// Select the average salaries grouped by city, only including cities with average salaries over 100000.
Root e = cq.from(Employee.class);
Expression avg = cb.avg(e.<Number>get("salary"));
cq.multiselect(avg, e.get("address").get("city"));
cq.groupBy(e.get("address").get("city"));
cq.having(cb.greaterThan(avg, 100000));

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria 4/8
06/10/2018 EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Criteria - Eclipsepedia

Where
Cookie settings

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
where API on CriteriaQuery with any Predicate objects. A Predicate is obtained using a comparison operation, or a logical operation on
CriteriaBuilder. The isNull, isNotNull, and in operations can also be called on Expression. The not operation can also be called on Predicate

Comparison operations defined on CriteriaBuilder


Operation Description Example

equal, notEqual equal cb.lessThan(e.get("firstName"), "Bob")

lessThan, lt less than cb.lessThan(e.get("salary"), 100000)

greaterThan, gt greater than cb.greaterThan(e.get("salary"), cb.parameter(Integer.class, "sal"))

lessThanOrEqualTo, le less than or equal cb.lessThanOrEqualTo(e.get("salary"), 100000)

greaterThanOrEqualTo,
greater than or equal cb.greaterThanOrEqualTo(e.get("salary"), cb.parameter(Integer.class, "sal"))
ge
cb.or(cb.like(e.get("firstName"), "A%")
evaluates if the two string match, '%' and '_' are valid
like, notLike
wildcards, and ESCAPE character is optional cb.notLike(e.get("firstName"), "%._%", '.'))

between evaluates if the value is between the two values cb.between(e.<String>get("firstName"), "A", "C"))

cb.isNull(e.get("endDate"))
compares the value to null, databases may not allow or
isNull
have unexpected results when using = with null e.get("endDate").isNull()

cb.in(e.get("firstName")).value("Bob").value("Fred").value("Joe")

in evaluates if the value is contained in the list e.get("firstName").in("Bob", "Fred", "Joe")

e.get("firstName").in(cb.parameter(List.class, "names")

Logical operations defined on CriteriaBuilder:

Logical operations defined on CriteriaBuilder


Operation Description Example

and and two or more predicates together cb.and(cb.equal(e.get("firstName"), "Bob"), cb.equal(e.get("lastName"), "Smith"))

or or two or more predicates together cb.or(cb.equal(e.get("firstName"), "Bob"), cb.equal(e.get("firstName"), "Bobby"))

cb.not(cb.or(cb.equal(e.get("firstName"), "Bob"), cb.equal(e.get("firstName"), "Bobby")))


not negate a predicate
cb.or(cb.equal(e.get("firstName"), "Bob"), cb.equal(e.get("firstName"), "Bobby")).not()

Predicate where = cb.conjunction();


if (name != null) {
conjunctionpredicate for true where = cb.and(where, cb.equal(e.get("firstName"), name);
}

Predicate where = cb.disjunction();


if (name != null) {
disjunctionpredicate for false where = cb.or(where, cb.equal(e.get("firstName"), name);
}

Subquery
Subqueries can be used in the Criteria API in the select, where, order, group by, or having clauses. A subquery is created from a CriteriaQuery using the
subquery operation. Most subquery usage restricts the subquery to returning a single result and value, unless used with the CriteriaBuilder exists, all,
any, or some operations, or with an in operation.
Subquery examples

CriteriaBuilder cb = em.getCriteriaBuilder();
 
// Find all manager that only manager below average employees.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
Subquery sq = cq.subquery(Employee.class);
Root e2 = cq.from(Employee.class);
sq.where(cb.and(e2.get("manager").equal(e), cb.equal(e2.get("productivity"), "below average").not());
cq.where(cb.exists(sq).not());
Query query = em.createQuery(cq)
List<Employee> = query.getResultList();
 
// Find the employee with the lowest salary.
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
Subquery sq = cq.subquery(Employee.class);
Root e2 = cq.from(Employee.class);
sq.select(e2.get("salary"));
cq.where(cb.lessThan(e.get("salary"), cb.all(sq)));
Query query = em.createQuery(cq)
List<Employee> = query.getResultList();

Parameters
Parameters can be defined using the parameter API on CriteriaBuilder. 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 1 not 0.

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria 5/8
06/10/2018 EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Criteria - Eclipsepedia
Named parameter
Cookie criteria example
settings
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.where(cb.equal(e.get("firstName"), cb.parameter(String.class, "first")), cb.equal(e.get("lastName"), cb.parameter(String.class, "last")));
Query query = em.createQuery(cq)
query.setParameter("first", "Bob");
query.setParameter("last", "Smith");
List<Employee> = query.getResultList();

Positional parameter criteria example

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root e = cq.from(Employee.class);
cq.where(cb.equal(e.get("firstName"), cb.parameter(String.class)), cb.equal(e.get("lastName"), cb.parameter(String.class)));
Query query = em.createQuery(cq)
query.setParameter(1, "Bob");
query.setParameter(2, "Smith");
List<Employee> = query.getResultList();

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

CriteriaBuilder database functions


Function Description Example

diff subtraction cb.diff(e.<Number>get("salary"), 1000)

sum addition cb.sum(e.<Number>get("salary"), 1000)

prod multiplication cb.prod(e.<Number>get("salary"), 2)

quot division cb.quot(e.<Number>get("salary"), 2)

cb.abs(
abs absolute value cb.diff(e.<Number>get("salary"), e.get("manager").<Number>get("salary")))

cb.selectCase(e.get("status")).
when(0, "active").
when(1, "consultant").
otherwise("unknown")
selectCase defines a case statement
cb.selectCase().
when(cb.equal(e.get("status"), 0), "active").
when(cb.equal(e.get("status"), 1), "consultant").
otherwise("unknown")

coalesce evaluates to the first non null argument value cb.coalesce(cb.concat(e.<Number>get("salary"), 0)

cb.concat(
concat concatenates two or more string values cb.concat(e.<String>get("firstName"), " "), e.<String>get("lastName"))

currentDate the current date on the database cb.currentDate()

currentTime the current time on the database cb.currentTime()

currentTimestampthe current date-time on the database cb.currentTimestamp()

length the character/byte length of the character or binary value cb.length(e.<String>get("lastName"))

the index of the string within the string, optionally starting at a


locate cb.locate("-", e.<String>get("lastName"))
start index

lower convert the string value to lower case cb.lower(e.<String>get("lastName"))

computes the remainder of dividing the first integer by the


mod cb.mod(e.<Integer>get("hoursWorked"), 8)
second
returns null if the first argument to equal to the second
nullif cb.nullif(e.<Number>get("salary"), 0)
argument, otherwise returns the first argument

sqrt computes the square root of the number cb.sqrt(e.<Number>get("salary"))

the substring from the string, starting at the index, optionally


substring cb.substring(e.<String>get("lastName"), 0, 2)
with the substring size
cb.trim(TrimSpec.TRAILING, e.<String>get("lastName"))

trims leading, trailing, or both spaces or optional trim


trim cb.trim(e.<String>get("lastName"))
character from the string
cb.trim(TrimSpec.LEADING, '-', e.<String>get("lastName"))

upper convert the string value to upper case cb.upper(e.<String>get("lastName"))

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
CriteriaBuilder and some are on specific Expression interfaces.

JPQL special functions


https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria 6/8
06/10/2018 EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Criteria - Eclipsepedia
Cookie settings
Function Description Example
the index of the ordered List element, only supported when
Root e = cq.from(Employee.class);
@OrderColumn is used in the mapping, ListJoin toDo = e.joinList("toDoList");
index defined on the ListJoin interface obtained from a From cq.multiselect(e, toDo);
cq.where(cb.equal(toDo.index(), 1));
element using the joinList operation

the key or value of the Map element, defined on the MapJoin Root e = cq.from(Employee.class);
MapJoin p = e.joinMap("priorities");
key, value interface obtained from a From element using the joinMap cq.multiselect(e, p.value());
operation cq.where(cb.equal(p.key(), "high"))

the size of the collection relationships, this evaluates to a sub-


size cb.greaterThan(cb.size(e.<Collection>get("managedEmployees")), 2)
select, defined on the CriteriaBuilder
isEmpty, evaluates to true if the collection relationship is empty or not, this
cb.isEmpty(e.<Collection>get("managedEmployees"))
isNotEmpty evaluates to a sub-select, defined on the CriteriaBuilder
evaluates to true if the collection relationship contains the value,
isMember,
this evaluates to a sub-select, defined on the cb.isMember("write code", e.<Collection>get("responsibilities"))
isNotMember
CriteriaBuilder
the inheritance discriminator value, defined on any Path
type cb.equal(p.type(), LargeProject.class)
expression
can be used to cast an un-typed expression to a typed cb.mod(e.get("id").as(Integer.class), 2)
as expression, EclipseLink also allows this to down cast inherited
types cb.greaterThan(p.as(LargeProject.class).get("budget"), 1000000)

call a database specific function, defined on the


function cb.greaterThan(cb.function("TO_NUMBER", Number.class, p.get("areaCode")), 613)
CriteriaBuilder

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 _ 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.
More more information on the JPA meta-model and on how to generate the meta-model see, Metamodel (/index.php?
title=EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Metamodel&action=edit&redlink=1)
Metamodel criteria example

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root<Employee> e = cq.from(em.getMetamodel().entity(Employee.class));
cq.where(cb.equal(e.get(Employee_.firstName), "Bob"), cb.equal(e.get(Employee_.lastName), "Smith"));
Query query = em.createQuery(cq)
List<Employee> = query.getResultList();

Tuple Queries
A Tuple 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 Tuple is a map-like structure that allows the results to be retrieved by name or index.
Tuple query examples

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root e = cq.from(Employee.class);
cq.multiselect(e.get("firstName").alias("first"), employee.get("lastName").alias("last"));
Query query = em.createQuery(cq);
List<Tuple> results = query.getResultList();
String first = results.get(0).get("first");
String last = results.get(0).get("last");

JpaCriteriaBuilder and EclipseLink Extensions


EclipseLink's Criteria API support has fewer restrictions than what JPA specifies. In general sub-queries and object path expressions are allowed in most places,
including:

Sub-queries in the select, group by, and order clauses;


Sub-query usage with functions;
in usage with object path expressions;
Order by usage with object path expressions.
EclipseLink's Criteria API support is built on top of EclipseLink native Expression API. EclipseLink provides the JpaCriteriaBuilder interface to allow the
conversion of native Expression objects to and from JPA Expression objects. This allows the EclipseLink native Expression API to be mixed with the JPA
Criteria API. Support for JpaCriteriaBuilder was added in EclipseLink 2.4.
The EclipseLink native Expression API provides the following additional functionality:
Additional database functions (over 80 database functions are supported);
Usage of custom ExpressionOperators;
Embedding of SQL within an Expression query;
Usage of sub-selects in the from clause;
on clause support;
Access to unmapped columns and tables;
Historical querying.
EclipseLink Expressions can be combined with EclipseLink DatabaseQuerys to provide additional functionality:

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria 7/8
06/10/2018 EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Criteria - Eclipsepedia
Unions,
Cookie intersect and except clauses;
settings
Hierarchical connect by clauses;
Batch fetching.
JpaCriteriaBuilder native Expression example

JpaCriteriaBuilder cb = (JpaCriteriaBuilder)em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Employee.class);
Root e = cq.from(Employee.class);
cq.where(cb.fromExpression(cb.toExpression(e.get("firstName")).regexp("^Dr\.*")));

(http://wiki.eclipse.org/EclipseLink)

Named Queries (/index.ph


JPQL title=EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Named&action=edit&redlink=
(/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL) (/File:Elug_next_icon.pn
(/File:Elug_home_icon.png) EclipseLink Home (/EclipseLink)
JPA User Guide: (/EclipseLink/UserGuide/JPA)Table of Contents (/EclipseLink/UserGuide/JPA), (http://www.google.com/cse/home?
cx=016171230611334810008:y5kxq4rqd8s&hl=en)Search (http://www.google.com/cse/home?cx=016171230611334810008:y5kxq4rqd8s&hl=en)
How to contribute to this guide... (/DocumentationGuidelines)

This page was last modified 07:47, 12 August 2016 by Senen de Diego (/index.php?title=User:Senen.electrodh.com&action=edit&redlink=1). Based on work by James
(/User:James.sutherland.oracle.com), Ben Gelernter (/User:Ben.gelernter.oracle.com) and Rick Sapir (/User:Rick.sapir.oracle.com).

Copyright © Eclipse Foundation, Inc. All Rights Reserved.

    
(https://twitter.com/EclipseFdn)
 (https://plus.google.com/+Eclipse)
 (https://www.facebook.com/eclipse.org)
 (https://www.youtube.com/user/EclipseFdn)
 (https://www.linkedin.com/company/eclipse-

foundation)

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria 8/8

You might also like