Introducing the Hibernate Query API
The Hibernate Query API lets you write the previous 36-line example in
Listing 1 using just 17 lines of quite readable code (see
Listing 2 for the full example):
...
Criteria criteria
= session.createCriteria(Accommodation.class);
if (startDate != null) {
criteria.add(Expression.ge("availabilityDate",
startDate);
}
if (endDate != null) {
criteria.add(Expression.le("availabilityDate",
endDate);
}
// and so on
Listing 2. Using the Hibernate Criteria API for Multi-Criteria Queries
public List searchAccommodation(Date startDate,
Date endDate,
Country country,
AccommodationType type,
Integer capacity)
Criteria criteria
= session.createCriteria(Accommodation.class);
if (startDate != null) {
criteria.add(Expression.ge("availabilityDate",
startDate);
}
if (endDate != null) {
criteria.add(Expression.le("availabilityDate",
endDate);
}
if (country != null) {
criteria.add(Expression.eq("country",country);
}
if (capacity != null) {
criteria.add(Expression.ge("capacity",capacity);
}
if (type != null) {
criteria.add(Expression.eq("type",type);
}
List results = criteria.list();
//
// Execute the query
//
return query.list();
}
Let's take a closer look at how you create and use the Criteria object. The principal class in the API is the Criteria class. You create a Criteria object using the createCriteria() method in the Hibernate session object:
Criteria criteria
= session.createCriteria(Accommodation.class);
Once created, you build the query by adding Criterion objects, obtained from the Expression class:
criteria.add(Expression.ge("availabilityDate",
startDate));
criteria.add(Expression.le("availabilityDate",
endDate));
You can also add 'order by' clauses:
criteria.addOrder( Order.asc("availabilityDate") )
You may use methods such as setFirstResult(), setMaxResults(), and setCacheable() to customize the query behavior in the same way as in the Query interface. So, to get the first 10 results, use the following commands:
criteria.setFirstResult(0)
criteria.setMaxResults(10)
Finally, to execute the query, invoke the list() method (or, if appropriate, the uniqueResult() method). Here is the full example:
List rooms = session.createCriteria(Accommodation.class)
.add(Expression.ge("availabilityDate",
startDate);
.add(Expression.le("availabilityDate",
endDate);
.addOrder( Order.asc("availabilityDate") )
.setFirstResult(0)
.setMaxResults(10)
.list();