Reputation: 1217
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
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
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