我有一个这样的课:
class Foo {
String bar
}
Run Code Online (Sandbox Code Playgroud)
我试图获取Foo其barString在列表中的所有对象的ID bars.我尝试了几种方法,总是收到同样的错误:
java.lang.String cannot be cast to java.util.Collection
Run Code Online (Sandbox Code Playgroud)
我试过的一些事情:
def ids = Foo.findAllByBarInList( bars )*.id
def ids = Foo.findAllByBarInList( bars ).collect{ it.id }
def ids = Foo.findAllByBarInList( bars ).collect{ it -> it?.id }
Run Code Online (Sandbox Code Playgroud)
更新:
我正在bars使用split进行制作,因此它是一个数组而不是列表.它把我扔了,因为Foo.findAllByBarInList( bars )我的Foo对象恢复得很好,只有当我试图收集它时才会失败.我现在改为bars使用tokenize,一切都很顺利.
Bur*_*ith 14
只要bars是List,这对我有用
def bars = ['bar1', 'bar3']
def ids = Foo.findAllByBarInList(bars)*.id
Run Code Online (Sandbox Code Playgroud)
但是,如果你想要的只是id字段,从数据库中提取整个域类实例是一种浪费.现在只有一个领域,但实际上它可能是一个更大的表.所以我使用HQL查询:
def ids = Foo.executeQuery(
'select f.id from Foo f where f.bar in (:bars)',
[bars: bars])
Run Code Online (Sandbox Code Playgroud)