For generic groovy classes (i.e. classes other than GORM), David is right that flatten
and unique
best.
In your example, however, it looks like you are using GORM domain objects in a many-to-many relationship (otherwise you will not need a unique constraint).
For a domain class, you are better off using either HQL or criteria to do this in one step. An added benefit is that the SQL generated for it is much more efficient.
Here's the HQL for getting unique Bar
identifiers that are associated with any Foo
many-to-many relationship:
Bar.executeQuery("select distinct b.id from Foo f join f.bars b")
The criteria for this will look like this:
Foo.withCriteria { bars { projections { distinct("id") } } }
One βproblemβ using this method is that HQL is not supported in unit tests (and probably never will be), and Query Criteria with connection table projections are broken down into 2.0.4 unit tests . Thus, any tests around this code would either have to mock or use an integration test.
source share