Search code examples
grailsmultiple-columnsfindby

findBy multiple attributes (findAllWhere)


I have an object from which I must filter certain attributes, some of which could also be "null". I have a Filter object and a Product object.

In the Filter object I have certain attributes reflecting the Product object which can be filled out or be left blank. Here a shortened view on the classes.

Product: String name, Boolean isEmpty, ...., belongsTo [Producer, Distributor]...


Filter: Boolean isEmpty, ... belongsTo [Producer, Distributor]...

With this filter I can search for all Products having certain attributes (empty, Producer, Distributor).

I have an export functionality where I can select the filter and it outputs the information based on that selection for the Products.

As all of these attributes can be null, but also contain a value, I first of thought to construct an own search query (combining strings etc) to construct an SQL-string and then using Product.findAll(string_query, string_params). But as this is quite tedious, I changed it now to someting like this:

if(filter.producer)
    prods = Product.findAllWhere(producer:filter.producer)
if(filter.distributor)
    prods =  prods.findAll {it.distributor == filter.distributor}
if(filter.isEmpty!=null) //as it could be NULL but also false/true
    prods =  prods.findAll {it.isEmpty == filter.isEmpty}

But this becomes quite a larger task if I have 10-15 attributes to be filtered. I'm not very experienced with Grails or Groovy but I guess this can be solved easier, right?


Solution

  • I believe you'll find Grails Criteria queries to be a very nice way to accomplish tasks like this. See:

    Your sample might look something like this when expressed as a criteria query:

    def prods = Product.createCriteria().list {
        if(filter.producer) eq("producer", filter.producer)
        if(filter.distributor)  eq("distributor", filter.distributor)
        if(filter.isEmpty != null) eq("isEmpty", filter.isEmpty)
    }