Criteria queries start by obtaining a Criteria
object from the Session, using the
createCriteria( ) method
to identify the primary class (and thus table) on which the query is to be
performed. Restrictions, projections, and orderings are then attached to the
query using the factories described below, making it a very powerful and
convenient interface.
This excerpt is from Harnessing Hibernate . This guide is an ideal introduction to Hibernate, the framework that lets Java developers work with information from a relational database easily and efficiently. Databases are a very different world than Java objects, and with Hibernate, bridging them is significantly easier. This new edition lets you explore the system, from download and configuration through a series of projects that demonstrate how to accomplish a variety of practical goals.
Hibernate provides the class
org.hibernate.criterion.Restrictions as a factory
for creating the Criterion instances you use to
narrow down the objects (rows) you want from criteria queries.
Restrictions defines a bunch of static methods you
can invoke to conveniently create each of the standard
Criterion implementations available in Hibernate,
using parameters you supply. These criteria are used to determine which
persistent objects from the database are included in the results of your
query. The following table provides a summary of the available
options.
| Method | Parameters | Purpose |
|---|---|---|
allEq
| Map properties | A shortcut for requiring several properties to
have particular values. The keys of the supplied map are the names
of the properties you want to constrain, while the values in the
map are the target values each property must equal if an entity is
to be included in the query results. The returned
Criterion ensures that each named
property has the corresponding value. |
and
| Criterion lhs, Criterion rhs | Builds a compound
Criterion that requires both halves to be
met in order for the whole to succeed. See also
conjunction( ). |
between
| String property,
Object low, Object
high | Requires the value of the named property to
fall between the values of low and
high. |
conjunction
| None | Creates a Conjunction
object which can be used to build an “and” criterion with as many
pieces as you need. Simply call its
add( ) method with each of the
Criterion instances you want to check.
The conjunction will be true if and only if all its component
criteria are true. This is more convenient than building a tree of
and( ) criteria “by hand.” The
add( ) method of the
Criteria interface acts as though it
contains a Conjunction. |
disjunction
| None | Creates a Disjunction
object that can be used to build an “or” criterion with as many
pieces as you need. Simply call its
add( ) method with each of the
Criterion instances you want to check. The
disjunction will be true if any of its component criteria are
true. This is more convenient than building a tree of
or( ) criteria “by hand.” See Example 8.10. |
eq
| String property,
Object value | Requires the named property to have the specified value. |
eqProperty
| String property1,
String property2 | Requires the two named properties to have the same value. |
ge
| String property,
Object value | Requires the named property to be greater than or equal to the specified value. |
geProperty
| String property1,
String property2 | Requires the first named property to be greater than or equal to the second. |
gt
| String property,
Object value | Requires the named property to be greater than the specified value. |
gtProperty
| String property1,
String property2 | Requires the first named property to be greater than the second. |
idEq
| Object value | Requires the identifier property to be equal to the specified value. |
ilike
| String property,
Object value | A case-insensitive “like” operator. See
like. |
ilike
| String property,
String value,
MatchMode mode | A case-insensitive “like” operator for people
who don’t want to mess with “like” syntax and just want to match a
substring. MatchMode is a type-safe
enumeration with values START,
END, ANYWHERE, and EXACT. This method adjusts the syntax of
value to reflect the kind
of matching specified by mode, then proceeds like the
two-parameter ilike( ). |
in
| String property, Collection values | A shortcut for allowing the named property to
have any of the values contained in the collection. This is more
convenient than building up a
disjunction( ) of
eq( ) criteria “by hand.” |
in
| String property,
Object[] values | A shortcut for allowing the named property to
have any of the values contained in the array. This is more
convenient than building up a
disjunction( ) of
eq( ) criteria “by hand.” |
isEmpty
| String property | Requires the named collection property to be empty (have zero length). |
isNotEmpty
| String property | Requires the named collection property to be have one or more elements. |
isNotNull
| String property | Requires the named property to have a value
other than null. |
isNull
| String property | Requires the named property to be null. |
le
| String property,
Object value | Requires the named property to be less than or equal to the specified value. See Example 8.3. |
leProperty
| String property1,
String property2 | Requires the first named property to be less than or equal to the second. |
like
| String property,
Object value | Requires the named property to be “like” the
specified value (in the sense of the SQL like
operator, which allows simple substring matching). See Examples
8.8 and 8.16. |
like
| String property,
String value,
MatchMode mode | A “like” operator for people who don’t want to
mess with “like” syntax and just want to match a substring. See
ilike( ) for more details. |
lt
| String property,
Object value | Requires the named property to be less than the specified value. |
ltProperty
| String property1,
String property2 | Requires the first named property to be less than the second. |
naturalId
| None | Allows selection through a multicolumn
“natural business key” mapped using natural-id. |
ne
| String property,
Object value | Requires the named property to have any value other than the specified value. |
neProperty
| String property1,
String property2 | Requires the two named properties to have different values. |
not
| Criterion expression | Negates the supplied
Criterion (if it matched, this one fails,
and vice versa). |
or
| Criterion lhs, Criterion rhs | Builds a compound
Criterion that succeeds if either of its
halves matches. See also
disjunction( ). |
sizeEq
| String property, int size | Requires the named collection property to have the specified number of elements. |
sizeGe
| String property, int size | Requires the named collection property to have at least the specified number of elements. |
sizeGt
| String property, int size | Requires the named collection property to have more than the specified number of elements. |
sizeLe
| String property, int size | Requires the named collection property to have no more than the specified number of elements. |
sizeLt
| String property, int size | Requires the named collection property to have fewer than the specified number of elements. |
sizeNe
| String property, int size | Requires the named collection property to have
a different number of elements than size. |
sqlRestriction
| String sql | Applies a constraint expressed in the native SQL dialect of the underlying database system. This can be very powerful, but be aware it might lead to loss of portability. |
sqlRestriction
| String sql, Object[]
values,
Type[] types | Applies a constraint expressed in the native SQL of the underlying database, with the supplied JDBC parameters. This can be very powerful, but be aware it might lead to loss of portability. |
sqlRestriction
| String sql, Object
value,
Type type | Applies a constraint expressed in the native SQL of the underlying database, with the supplied JDBC parameter. This can be very powerful, but be aware it might lead to loss of portability. |
When specifying query text for the
sqlRestriction( ) methods, any occurrences of
the string “{alias}” within the query
will be replaced by the actual alias of the table on which the query is
being performed.
Many of these methods accept Criterion
instances as arguments, allowing you to build compound criteria trees with
as much complexity as you need.
conjunction( ) and disjunction( ) return objects
that make it even easier to add criteria, by returning objects with
add( ) methods you can call as many times as
you’d like to add criteria. If your query gets sufficiently complex,
however, it might be easier to express and understand in
HQL. There are also a few remaining kinds of queries
that are not yet supported by this API, so you may not
always be able to avoid HQL. But that’s becoming
increasingly rare—most of the kinds of bread-and-butter queries that come
up all the time in application development are expressed very naturally
and easily in this API, leading to readable and compact
Java code that can be checked for correctness at compile-time.
Hibernate provides the class org.hibernate.criterion.Projections
as a factory for creating the Projection instances
you use to narrow down the properties (columns) you want from criteria
queries, and requesting the calculation of aggregate values. Projections defines static methods you
can invoke to conveniently create each of the standard
Projection implementations available in Hibernate,
using parameters you supply. These projections are used to narrow, group
or transform the properties that get included in the results of your
query. Here is a summary of the available options.
| Method | Parameters | Purpose |
|---|---|---|
alias
| Projection projection,
String alias | Assigns an alias (name) to the projection, so it can be referred to in other places within your Criteria query (such as for grouping, ordering, and the like). |
avg
| String property | Calculates the average of the named property. |
count
| String property | Calculates the number of times this property appears in the results. |
countDistinct
| String property | Calculates the number of distinct (different) values this property has within the results. |
distinct
| Projection projection | Causes only unique values to be returned from the projection (eliminates duplicate values). |
groupProperty
| String property | Causes results to be grouped by the specified property (useful when calculating aggregate values). See Example 8.15. |
id
| None | Returns the object’s identifier as an element of the projection (regardless of what the name of the identifier property may be). |
max
| String property | Calculates the largest value of the named property. See Example 8.15. |
min
| String property | Calculates the smallest value of the named property. |
projectionList
| None | Creates a new projection list, for requesting more than one projected value. See Example 8.14. |
property
| String property | Includes the value of the named property in the projection. See Example 8.13. |
rowCount
| None | Calculates the total number of results returned. See Example 8.15. |
sqlGroupProjection
| String sql, String
groupBy,
String[] columnAliases, Type[] types | Lets you use database-specific SQL code to
perform the projection; groupBy can contain a SQL “GROUP
BY” clause. You need to tell Hibernate the names and types
of any column aliases your projection returns. |
sqlProjection
| String sql, String[] columnAliases,
Type[] types | Lets you use database-specific SQL code to
perform the projection; you can perform grouping using
groupProperty( ) projections, above.
You need to tell Hibernate the names and types of any column
aliases your projection returns. |
sum
| String property | Calculates the arithmetic sum of the values of the named property. |
You can ask Hibernate (and thereby, the underlying database
system) to sort your results in a particular order. The
class org.hibernate.criterion.Order represents
these ordering requests, and offers two static factory methods for
creating the instances you need, which can then be added to your query.
Once you’ve obtained your Order instance, you can call
the nonstatic method ignoreCase( ) on it if
you would like your results sorted in a case-insensitive way.
| Method | Parameters | Purpose |
|---|---|---|
asc
| String property | Creates an ordering that will sort results in ascending order by the named property. See Example 8.6. |
desc
| String property | Creates an ordering that will sort results in descending order by the named property. |
In the methods we’ve been looking at so far, you start
with the criterion, projection, or order you’re interested in
creating, and then supply the name of the property with which you want to
work as a parameter. The Criteria API also lets you work in the opposite
direction, starting with the property and then calling a method to build a
criterion or projection based on it. The class
org.hibernate.criterion.Property is a factory for
creating the Property instances you use when you
prefer this approach. Property defines a single
static method, forName( ), which you can
invoke to create an instance representing a particular property. Once
you’ve got that instance, you can call one of the following methods to
create criteria, projections and orderings based on the property it
represents. Here is a list of the more commonly useful methods; the ones
we omit have to do with detached criteria and subqueries, which are beyond
the scope of this book. When you want to learn about them, see the
Advanced query options chapter of Java
Persistence with Hibernate or Detached
queries and subqueries in the online reference.
| Method | Parameters | Purpose |
|---|---|---|
asc
| None | Creates an Order that
will sort results in ascending order by the property. |
avg
| None | Creates a Projection
that returns the average of the property’s values. |
between
| Object min, Object
max | Creates a Criterion
that requires the property have a value between min and max. |
count
| None | Creates a Projection
that returns the number of times the property appears in the
results.[a] |
desc
| None | Creates an ordering that will sort results in descending order by the named property. |
eq
| Object value | Creates a Criterion
that requires the property to equal the supplied value.[b] |
eqProperty
| Property other | Creates a Criterion
that requires the property to equal another property, represented
by other. |
eqProperty
| String property | Creates a Criterion
that requires the property to equal another property, named by
property. |
ge
| Object value | Creates a Criterion
that requires the property to be greater than or equal to the
specified value.[b] |
geProperty
| Property other | Creates a Criterion
that requires the property to be greater than or equal to another
property, represented by other. |
geProperty
| String property | Creates a Criterion
that requires the property to be greater than or equal to another
property, named by property. |
getProperty
| String property | Extracts the named component property of the
current property (which is presumably a compound property).
Returns another Property instance. |
group
| None | Creates a Projection
that requests results be grouped by values of the
property. |
gt
| Object value | Creates a Criterion
that requires the property to be greater than the specified
value.[b] |
gtProperty
| Property other | Creates a Criterion
that requires the property to be greater than another property,
represented by other. |
gtProperty
| String property | Creates a Criterion
that requires the property to be greater than another property,
named by property. |
in
| Collection values | Creates a Criterion
that requires the supplied collection to contain the
property. |
in
| Object[] values | Creates a Criterion
that requires the property to be equal to any element of the
array. |
isEmpty
| None | Creates a Criterion
that requires the property to be empty (be a collection with
length zero). |
isNotEmpty
| None | Creates a Criterion
that requires the property to be a collection with at least one
element. |
isNotNull
| None | Creates a Criterion
that requires the property to have a non-null value. |
isNull
| None | Creates a Criterion
that requires the property to have a null value. |
le
| Object value | Creates a Criterion
that requires the property to be less than or equal to the
specified value.[b] |
leProperty
| Property other | Creates a Criterion
that requires the property to be less than or equal to another
property, represented by other. |
leProperty
| String property | Creates a Criterion
that requires the property to be less than or equal to another
property, named by property. |
like
| Object value | Creates a Criterion
that requires the property to be “like” the specified value (in
the sense of the SQL like operator, which allows
simple substring matching).[b] |
like
| String value,
MatchMode mode | A version of “like” for people who don’t want
to mess with “like” syntax and just want to match a substring.
MatchMode is a type-safe enumeration with
values START, END, ANYWHERE, and EXACT. This method adjusts the syntax of
value to reflect the kind
of matching specified by mode, then proceeds like the
single-parameter like( ) earlier.[b] |
lt
| Object value | Creates a Criterion
that requires the property to be less than the specified
value.[b] |
ltProperty
| Property other | Creates a Criterion
that requires the property to be less than another property,
represented by other. |
ltProperty
| String property | Creates a Criterion
that requires the property to be less than another property, named
by property. |
max
| None | Creates a Projection
that returns the largest of the property’s values. |
min
| None | Creates a Projection
that returns the smallest of the property’s values. |
ne
| Object value | Creates a Criterion
that requires the property to have any value other than the
specified value.[b] |
neProperty
| Property other | Creates a Criterion
that requires the property to have a different value than the
other. |
neProperty
| String property | Creates a
Criterion that requires the
property to have a different value than the named property. |
[a] The actual class returned,
[b] The actual class returned, | ||
If you enjoyed this excerpt, buy a copy of Harnessing Hibernate .
Copyright © 2009 O'Reilly Media, Inc.