Get identifiers of all objects in the list

I have a class like this:

class Foo { String bar } 

I am trying to get the identifiers of all Foo objects whose string bar String is in the list of bars . I tried several ways, always getting the same error:

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

Some of the things I tried:

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

UPDATE:

I did bars with split , so it was an array, not a list. This threw me away because Foo.findAllByBarInList( bars ) returned my Foo objects just fine, only when I tried to collect the identifiers did it fail. Now I do bars with tokenize , and all is well.

+6
source share
1 answer

This works for me while bars is a list

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

But if all you need is an id field, it is a waste to pull all instances of the domain class from the database. At the moment there is only one field, but in practice this is most likely a large table. Therefore, I would use the HQL query:

 def ids = Foo.executeQuery( 'select f.id from Foo f where f.bar in (:bars)', [bars: bars]) 
+12
source

Source: https://habr.com/ru/post/920720/


All Articles