Java Reference
In-Depth Information
Listing 11.5. Retrieving all item names using a query root
The code in this listing will produce the following SQL query:
SELECT ITEM_NAME FROM ITEMS
Now that you know how to create a criteria root, let's look at predicate and join expres-
sions.
Expressions
Expressions are used in the
SELECT
,
WHERE
, and
HAVING
clauses. You use expressions
to specify what you want returned by the query or how you want the query constrained. Ex-
pressions are all rooted by the
javax.persistence.criteria.Expression<T>
interface. There are several notable subinterfaces including
Predicate
,
Join
, and
Path
. To get an instance of an expression, you use utility methods on the
Criteri-
aBuilder
. You'll notice that in many situations you need an expression to create an
expression. For example, consider the method signature on
lessThanOrEqualTo
of
CriteriaBuilder
:
Predicate lessThanOrEqualTo(Expression<? extends Y> x,
Expression<? extends Y> y)
You can see that this method takes two expressions and returns a predicate. Both expres-
sions make use of generics whose type must match—if you're comparing
Double
, both
must be
Double
and so on. To reference a column (property on an entity), you construct
a
Path
. As mentioned previously, a
Path
is a type of expression and you use the query
root to construct it by passing in the attribute from the meta-model. Because this can be a
bit confusing, let's look at the
findByDate
method in the next listing.