AlexCon
AlexCon

Reputation: 1217

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 ?

Upvotes: 1

Views: 572

Answers (2)

grantmcconnaughey
grantmcconnaughey

Reputation: 10719

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

Upvotes: 3

user800014
user800014

Reputation:

Person.where is a method that takes a Closure as argument. A feature that closures have is composition. Here's an example from Groovy Goodness:

def convert = { new Expando(language: it) }

def upper = { it.toUpperCase() }

// Composition.
def upperConvert = convert << upper

So you can do something like:

def defaultWhere = {
  age in 18..65
}

if(someRuntimeTest) {
  defaultWhere << {
    weight in 100..200
  }
}

Person.where(defaultWhere)

Upvotes: 1

Related Questions