Java Reference
In-Depth Information
Using Restrictions with Criteria
The Criteria API makes it easy to use restrictions in your queries to selectively retrieve objects;
for instance, your application could retrieve only products with a price over $30. You may add
these restrictions to a
Criteria
object with the
add()
method. The
add()
method takes an
org.hibernate.criterion.Criterion
object that represents an individual restriction. You can
have more than one restriction for a criteria query.
Although you could create your own objects implementing the
Criterion
object, or extend
an existing
Criterion
object, we recommend that you use Hibernate's built-in
Criterion
objects
from your application's business logic. For instance, you could create your own factory class that
returns instances of Hibernate's
Criterion
objects appropriately set up for your application's
restrictions.
Use the factory methods on the
org.hibernate.criterion.Restrictions
class to obtain
instances of the
Criterion
objects. To retrieve objects that have a property value that equals
your restriction, use the
eq()
method on
Restrictions
, as follows:
public static SimpleExpression eq(String propertyName, Object value)
We would typically nest the
eq()
method in the
add()
method on the
Criteria
object.
Here is an example of how this would look if we were searching for products with the name
“Mouse”:
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.eq("name","Mouse"));
List results = crit.list()
Next, we search for products that do
not
have the name “Mouse.” For this, we would use
the
ne()
method on the
Restrictions
class to obtain a not-equal restriction:
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.ne("name","Mouse"));
List results = crit.list();
n
Tip
You cannot use the not-equal restriction to retrieve records with a
NULL
value in the database for that
property (in SQL, and therefore in Hibernate,
NULL
represents the absence of data, and so cannot be com-
pared with data). If you need to retrieve objects with
NULL
properties, you will have to use the
isNull()
restriction, which we discuss further on in the chapter. You can combine the two with an
OR
logical expres-
sion, which we also discuss later in the chapter.
Instead of searching for exact matches, we can also retrieve all objects that have a prop-
erty matching part of a given pattern. To do this, we need to create an SQL
LIKE
clause, with
either the
like()
or the
ilike()
method. The
ilike()
method is case-insensitive. In either
case, we have two different ways to call the method:
public static SimpleExpression like(String propertyName, Object value)
or
Search WWH ::
Custom Search