Criteria Queries
Hibernate now features an intuitive, extensible criteria query API. For now, this API
is less powerful and than the more mature HQL query facilities. In particular, criteria
queries do not support projection or aggregation.
Creating a Criteria instance
The interface org.hibernate.Criteria represents a query against
a particular persistent class. The Session is a factory for
Criteria instances.
Narrowing the result set
An individual query criterion is an instance of the interface
org.hibernate.expression.Criterion. The class
org.hibernate.expression.Expression defines
factory methods for obtaining certain built-in
Criterion types.
Expressions may be grouped logically.
There are quite a range of built-in criterion types (Expression
subclasses), but one that is especially useful lets you specify SQL directly.
The {alias} placeholder with be replaced by the row alias
of the queried entity.
Ordering the results
You may order the results using org.hibernate.expression.Order.
Associations
You may easily specify constraints upon related entities by navigating
associations using createCriteria().
note that the second createCriteria() returns a new
instance of Criteria, which refers to the elements of
the kittens collection.
The following, alternate form is useful in certain circumstances.
(createAlias() does not create a new instance of
Criteria.)
Note that the kittens collections held by the Cat instances
returned by the previous two queries are not pre-filtered
by the criteria! If you wish to retrieve just the kittens that match the
criteria, you must use returnMaps().
Dynamic association fetching
You may specify association fetching semantics at runtime using
setFetchMode().
This query will fetch both mate and kittens
by outer join.
Example queries
The class org.hibernate.expression.Example allows
you to construct a query criterion from a given instance.
Version properties, identifiers and associations are ignored. By default,
null valued properties are excluded.
You can adjust how the Example is applied.
You can even use examples to place criteria upon associated objects.