Pascal DeMilly
Pascal DeMilly

Reputation: 731

grails findAll findAllWhere inconsistencies

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

Upvotes: 0

Views: 1372

Answers (1)

Aaron
Aaron

Reputation: 546

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 }

Upvotes: 3

Related Questions