Parameters with new where queries in Grails 2.0

半城伤御伤魂 提交于 2019-12-13 13:18:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!