Archive for September 29th, 2006

Implement “Search results” using Hibernate

September 29, 2006

Hibernate Criteria API: Multi-Criteria Search Made Easy

Powerful, Elegant and Definitely Worth a Try,

that’s what the article says & it’s mighty true. Have seen quiet some people constructing these kind of queries using StringBuffer & stuff, but this is waaaay more elegant :)

..
Criteria criteria
= session.createCriteria(Accommodation.class);
if (startDate != null) {
criteria.add(Expression.ge("availabilityDate",
startDate);
}
if (endDate != null) {
criteria.add(Expression.le("availabilityDate",
endDate);
}

This beats

if (startDate != null) {
queryBuf.append(firstClause ? " where ": " and ");
queryBuf.append("a.availabiliyDate >=:startDate");
parameters.put("startDate",startDate);
firstClause = false;
}

any time !!