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();
// and so on
You can also fine-tune the way the QBE query is built in many ways, for example:
- Queries may be case sensitive or insensitive (
- Zero-valued fields may be ignored (
- Certain properties may be ignored (
- 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!