3 Replies Latest reply on Nov 6, 2007 5:08 AM by damianharvey

    Queries with optional arguments

      I've got a Seam application, and now I'm writing the search page. It has advanced search options. For example, there is a drop-down where the user can select the customer, so it will only find records for that customer. If the drop-down isn't used, it will find records from any customer.

      An obvious way to do this is logic like:

      if(selectedCustomer != null)
       queryString += "and invoice.customer = :customer ";
       // note the space at the end


      followed by:

      if(selectedCustomer != null)
       query.setParameter("customer", selectedCustomer);


      This is clunky, run-time debugged, error-prone. Leave off a space at the end, and it's a bug that might not show up until just the right parameters are set. This looks like the old days of hand-assembled SQL mess.

      In Hibernate, there was an object-oriented query construction system, called Criteria queries, where you can add terms to the query by creating objects (sub-classes of Criteria). That would be a natural way to do this type of advanced search thing, but I'm not seeing an EJB way to do it.

      Does my question make sense? And is there a good solution, other than the obvious one of having if statements for both putting together the query string, and then a second time for adding params?

      (As an aside, it seems like Hibernate had a lot of nice features that didn't make it into EJB 3. I realize that Hibernate is the underpinning of JBoss EJB3, but it's a shame some of these features didn't make it.)