7

我有这样的课:

class Foo {
    String bar
}

我正在尝试获取其String 在 list 中的所有Foo对象的 ID 。我尝试了几种方法,总是收到相同的错误:barbars

java.lang.String cannot be cast to java.util.Collection

我尝试过的一些事情:

def ids = Foo.findAllByBarInList( bars )*.id
def ids = Foo.findAllByBarInList( bars ).collect{ it.id }
def ids = Foo.findAllByBarInList( bars ).collect{ it -> it?.id }

更新:

我正在bars使用split所以它是一个数组,而不是一个列表。它让我失望,因为Foo.findAllByBarInList( bars )我的对象很好地归还了Foo,只有当我试图收集 id 时它才失败。我现在barstokenize代替,一切都很好。

4

1 回答 1

14

只要bars是一个列表,它就对我有用

def bars = ['bar1', 'bar3']
def ids = Foo.findAllByBarInList(bars)*.id

但是,如果您想要的只是id字段,那么从数据库中提取整个域类实例是一种浪费。目前只有一个字段,但实际上它可能是一个更大的表。所以我会使用 HQL 查询:

def ids = Foo.executeQuery(
   'select f.id from Foo f where f.bar in (:bars)',
   [bars: bars])
于 2012-07-17T18:57:28.860 回答