如何使Groovy / Grails返回对象列表而不是对象列表列表? [英] How to make Groovy / Grails return a List of objects instead of a List of Lists of objects?

查看:236
本文介绍了如何使Groovy / Grails返回对象列表而不是对象列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的类:

  class Foo {
static hasMany = [bars:Bar]
}

当我写:

  Foo.getAll()

Foo 这样的对象:

  [Foo1,Foo2,Foo3] 

当我写:

  Foo.getAll()。bars 

code> Bar 对象,如下所示:

  [[Bar1,Bar2] ,Bar3],[Bar1,Bar4]] 

但我想要的是一个唯一的列表 Bar 这样的对象:

  [Bar1,Bar2,Bar3,Bar4] 

我的最终目标是拥有一个ids的唯一列表 code>对象,如下所示:

  [1,2,3,4] $ b $我已尝试过   /java/util/Collection.html#collect%28groovy.lang.Closure%29\">收集方法,我也试过了 spread operator ,但我没有运气。

解决方案

对于通用groovy类非GORM类),David是正确的,使用 flatten unique 是最好的办法。 >

在你的例子中,它看起来像是在多对多关系中使用GORM域对象(否则你不需要唯一性约束)。



对于一个域类,你最好使用HQL或者一个标准来做到这一点。另一个优点是为它生成的SQL效率更高。



这里是HQL获取独特的 Bar 与多对多关系中的任何 Foo 相关的ids:

  Bar.executeQuery(select distinct b.id from Foo f join f.bars b)

其标准如下:

  Foo.withCriteria {
bars {
{
distinct(id)
}
}
}

使用这种方法的一个问题是单元测试中不支持HQL(并且可能永远不会)和使用连接表投影的条件查询在2.0.4单元测试中被破坏。因此,围绕该代码的任何测试都需要被嘲笑或使用集成测试。


I have a class like this:

class Foo {
    static hasMany = [bars: Bar]
}

When I write:

Foo.getAll()

I get a list of Foo objects like this:

[ Foo1, Foo2, Foo3 ]

When I write:

Foo.getAll().bars

I get a list of lists of Bar object like this:

[ [ Bar1, Bar2 ], [ Bar2, Bar3 ], [ Bar1, Bar4 ] ] 

But what I want is a unique list of Bar objects like this:

[ Bar1, Bar2, Bar3, Bar4 ]

My end goal is to have a unique list of ids of the Bar object in the list above, like this:

[ 1, 2, 3, 4 ]

I have tried variations of the collect method and I have also tried the spread operator but I'm not having any luck.

解决方案

For generic groovy classes (i.e. non-GORM classes), David is correct that using flatten and unique is the best way to go.

In your example though, it looks like you're using GORM domain objects in a many-to-many relationship (otherwise you wouldn't need the uniqueness constraint).

For a domain class, you're best off using either HQL or a criteria to do this in one step. An additional advantage is that the SQL generated for it is much more efficient.

Here's the HQL for getting the unique Bar ids that are related to any Foo in a many-to-many relationship:

Bar.executeQuery("select distinct b.id from Foo f join f.bars b")

The criteria for this would look like:

Foo.withCriteria {
    bars {
        projections {
          distinct("id")
        }
    }
}

One "issue" with using this kind of method is that HQL is not supported in unit tests (and likely will never be) and Criteria queries with join table projections are broken in 2.0.4 unit tests. So any tests around this code would either need to be mocked or use an integration test.

这篇关于如何使Groovy / Grails返回对象列表而不是对象列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆