advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sidebar 1. When to Use Multi-Criteria Searches
Sidebar 2. Hibernate Joins
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
Average Rating: 4.3/5 | Rate this item | 33 users have rated this item.
Hibernate Criteria API: Multi-Criteria Search Made Easy (cont'd)

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();
advertisement

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!

Previous Page: Expressions  
John Ferguson Smart is project director at Aacom, a French IT firm specializing in J2EE solutions. He holds a PhD in computer science from the University of Aix-Marseille, France. His specialties are J2EE architecture and development and IT project management.
Page 1: IntroductionPage 3: Expressions
Page 2: Introducing the Hibernate Query APIPage 4: QBE: Query by Example
Please rate this item (5=best)
 1  2  3  4  5
advertisement