问题
Is it possible to use parameters when defining a where query in Grails 2.0? For example:
def query = Book.where {
id == it
}
Book sub = query.find(5)
I tried running that code, but it throws a MissingMethodException on the call to find. I also tried defining a variable before it, but it doesn't seem to work (as find returns null, even though I know it exists).
Long someId = 5
def query = Book.where {
id == someId
}
Book sub = query.find()
Any tricks? Being able to dynamically change the parameters of the query would be extremely useful.
(I know I could just use Book.get(5), but for simplicity sake, this seemed like the easiest example to pick)
回答1:
Seems like the way to do this is to define a closure as detachCriteria,
import grails.gorm.*
def callable = { id ->
id == id
} as DetachedCriteria<Book>
def query = Book.where( callable( id: 5 ) )
来源:https://stackoverflow.com/questions/8020572/parameters-with-new-where-queries-in-grails-2-0