advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Sidebar 1. When to Use Multi-Criteria Searches
Sidebar 2. Hibernate Joins
Partners & Affiliates
advertisement
advertisement
advertisement
Average Rating: 3/5 | Rate this item | 1 user has rated this item.
Email this articleEmail this article
 
Hibernate Criteria API: Multi-Criteria Search Made Easy
The Hibernate Criteria API, a powerful and flexible alternative to traditional HQL queries, makes writing all those tricky multi-criteria search functions—as well as dynamic queries in general—much easier. 

advertisement
ulti-criteria search functionalities, which allow combinations of many optional criteria fields, are common in modern Web-enabled business applications (see Sidebar 1. When to Use Multi-Criteria Searches). An example of this functionality is an online accommodations database (see Figure 1) that allows users to search accommodations by country, availability, type (hotel, bed and breakfast, etc.), and capacity. All the criteria are optional, and the user may use any combination of criteria.

Click to enlarge
Figure 1: A Multi-Criteria Search Screen

The traditional approach for a Hibernate developer to enable this sort of functionality generally involves building an HQL (Hibernate Query Language) query on the fly, based on the search criteria the user entered. Next, he or she uses this query string to create a Hibernate Query object and then sets the non-null parameter values. The code looks something like this:


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

(See Listing 1 for a full example. Note that the model has been simplified for the sake of readability. Accommodation availability data would normally be stored in a separate table, of course.)

Listing 1. A Traditional Approach for Building Multi-Criteria HQL Queries

public List searchAccommodation(Date startDate,
                               Date endDate,
                               Country country,
                               AccommodationType type,
                               Integer capacity)
    Map parameters = new HashMap();
    boolean firstClause = true;
    StringBuffer queryBuf 
           = new StringBuffer("from Accommodation a ");

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

    String hqlQuery = queryBuf.toString();
    Query query = session.createQuery(hqlQuery);
   
    //
    // Set query parameter values
    //
    Iterator iter = parameters.keySet().iterator();
    while (iter.hasNext()) {
        String name = (String) iter.next();
        Object value = map.get(name);
        query.setParameter(name,value);
    }
    //
    // Execute the query
    //
    return query.list();
}

This approach is cumbersome and error-prone. It is also risky in a team-development context, as inexperienced developers will often take dangerous short-cuts using this approach. During code review, I've often come across multi-criteria search functions using error-prone String concatenation, direct use of query parameters in the query string, and so on:


...
if (startDate != null) {
    if (firstClause) {
        query = query + " where ";
    } else {
        query = query + " and ";
    }
    query += " a.availabilityDate >= '" 
             + startDate + "'";
} 
// And so on...               

So, is there better way? Yes, there is: the Hibernate criteria API, a powerful and elegant technique for complex, dynamic search functionalities. Using the online accommodations database cited previously, this article examines the criteria API solution and its benefits.

  Next Page: Introducing the Hibernate Query API
Page 1: IntroductionPage 3: Expressions
Page 2: Introducing the Hibernate Query APIPage 4: QBE: Query by Example
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: BitLocker Encryption on Windows Server 2008
Go Parallel Article: Intel Thread Checker, Meet 20 Million LOC
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES