Search code examples
grailsgroovygrails-ormwhere-clause

constructing Grails/Groovy where query in run-time


Is it possible to construct such query in run-time in grails/groovy ?

Let's say I have:

def query = Person.where {
     age in 18..65
}

and in run-time I wanna add weight to it as :

def query = Person.where {
     age in 18..65
     weight in 100..200
}

possible ?


Solution

  • I would use Criteria Queries instead. They allow you to dynamically construct queries like you want very easily. For example, you could create a criteria like this:

    def result = Person.createCriteria {
        'in'("age", [18..65])
    
        if (params.includeWeight) {
            'in'("weight", [100..200])
        }
    }.list()