0

Given a Grails domain

class Person {
     String name
     int age
}

I can execute that query

Person.findAll { age >= 25 }

But when I execute this query it doesn't do any filtering

def query = { age >= 25 }
Person.findAll query

I tried cloning, or nulling owner and delegate of that closure before passing it as an argument and still not luck

Also looking at the source of GormStaticApi in org/grails/datastore/gorm/ I should also be able to do the following

Person.findAllWhere ([age: 25], [max: 10, offset:5])

but it does work even though

Person.findAllWhere ([age: 25]) works

Anybody knows why that is. I am using Grails 2.3.9

saw303
  • 8,051
  • 7
  • 50
  • 90
Pascal DeMilly
  • 681
  • 1
  • 6
  • 16

1 Answers1

3

The documentation says:

Note that you cannot pass a closure defined as a variable into the where method unless it has been explicitly cast to a DetachedCriteria instance

It should work if you explicitly cast it:

def query = { age >= 25 } as DetachedCriteria
Person.findAll query

Although it you wanted to create a reusable DetachedCriteria, it would be better to do:

def query = Person.where { age >= 25}

Then you can do things like:

query.list()
query.findAllBySomethingElse()
query.findAll { somethingelse == foo }
Aaron
  • 546
  • 3
  • 8
  • I'm accessing my DB through rest and was evaluating the different way of doing filtering I ended up creating a builder to a criteria using a JSON map as the query parameters something like { gt: [ 'age', 25 ] } thx for pointing to the doc. I missed that line. – Pascal DeMilly Aug 11 '14 at 01:58