【问题标题】:Get the IDs of all objects in a list获取列表中所有对象的 ID
【发布时间】:2012-07-17 18:38:17
【问题描述】:

我有这样的课:

class Foo {
    String bar
}

我正在尝试获取bar 字符串在列表bars 中的所有Foo 对象的ID。我尝试了几种方法,总是收到相同的错误:

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 }

更新:

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

【问题讨论】:

  • 我在这个问题中添加了 groovy 标签,因为 collect 方法和扩展运算符 *. 都基于 groovy。
  • 您确定要检查的列表已正确设置为列表吗?使用 def ids = Foo.findAllByBarInList( bars )*.id 对我有用。
  • 由于Grails 使用Groovy,我将去掉Groovy 标签,所以没有必要,这只是Grails 中Groovy 的使用,而不是Groovy 特定的问题。没有 Grails 经验的 Groovy 专家将无法为您提供帮助。同样,您可以省略 Java、GORM、Hibernate、Spring、Programming 标记;)

标签: grails


【解决方案1】:

只要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])

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多