Java Reference
In-Depth Information
The
CriteriaBuilder
interface we discussed in the previous section is used to con-
struct the
CriteriaQuery
instance. The
CriteriaBuilder
is also used to construct
the various pieces of a query that you'll pass into the
CriteriaQuery
methods. You
use the
CriteriaBuilder
as a factory to fabricate the selection, expression, predicates,
and ordering statements you need. The key methods of the
CriteriaQuery
interface
are shown in
table 11.12
along with the object types that they accept.
Table 11.12. Core
CriteriaQuery
methods
Method
Parameter type
Description
groupBy
Expression
Constructs the SQL groupBy construct
having
Expression
Constructs the SQL HAVING construct
Creates a query with multiple selec-
tions
multiselect
Selection
orderBy
Order
Constructs the SQL orderBy statement
select
Selection
Creates a single selection
where
Predicate
Creates the SQL WHERE clause
11.2.4. Query root
The query root is a challenging abstraction to explain. A query root defines the origin for
navigation—it's the entities you need as part of your query because they contain the prop-
erties you're going to use when constructing the SQL
WHERE
,
SELECT
, and
JOIN
expres-
sions. A query may have zero or more query roots. If you're not joining on multiple tables,
specifying specific properties you want to retrieve, or applying constraints to the values re-
trieved, it isn't necessary to create a query root. A query root is thus an object that you use
to construct expressions.
To create a query root, you invoke the
from
method on the
CriteriaQuery
instance.
Despite its name, invoking the
from
method doesn't mean that you're populating the SQL
FROM
clause; entities will only be added to the
FROM
clause if you actually use them
in constructing an expression. The object that's returned is a
javax.persistence
.criteria.Root
. You then subsequently use this object to build expressions.
To better understand how the query root is used, consider the simple example shown in the
following listing.