QBE: Query by Example
Another interesting approach is QBE. Basically, you instantiate one of your business objects with the corresponding values coming from the search screen. Hibernate then builds the corresponding query using the non-null field values:
Accommodation accommodationEx = new Accommodation();
accommodationEx.setCountry(country);
accommodationEx.setCapacity(capacity);
// and so on
Example example
= Example.create(accommodationEx)
.ignoreCase()
.excludeZeroes()
.excludeProperty("doNotUse")
.enableLike(MatchMode.ANYWHERE);
return getSession()
.createCriteria(Accommodation.class)
.add(example)
.add(Expression.between("availabilityDate",
startDate,
endDate))
.list();
You can also fine-tune the way the QBE query is built in many ways, for example:
- Queries may be case sensitive or insensitive (
ignoreCase()).
- Zero-valued fields may be ignored (
excludeZeroes()).
- Certain properties may be ignored (
excludeProperty()).
- And so on...
The interesting thing here is that, if you have a lot of text fields in your multi-criteria search screen, you can use QBE to initialize the text values, and then use Expression-based criterion objects to add further constraints. In fact, the Example object is just another Criterion. So you can mix and match QBE and Criteria-based querying as you need.
Powerful, Elegant and Definitely Worth a Try
The Hibernate criteria API is a powerful and elegant library, which is well adapted for implementing multi-criteria search functionalities where queries must be built on the fly. Using it in appropriate circumstances will result in cleaner, clearer, more reliable, and more maintainable code. Try it out!