Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the IDs of all objects in a list

Tags:

grails

I have a class like this:

class Foo {
    String bar
}

I am trying to get the IDs of all the Foo objects whose bar String is in the list bars. I have tried it several ways, always receiving the same error:

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

Some of the things I have 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 was making bars with split so it was an array, not a list. It threw me off because Foo.findAllByBarInList( bars ) returned my Foo objects just fine, only when I tried to collect the ids did it fail. I now make bars with tokenize instead and all is well.

like image 303
ubiquibacon Avatar asked Jul 17 '12 18:07

ubiquibacon


People also ask

How do I get a list of IDS?

You can find the ListId by navigating to the SharePoint list, and then copying the URL, and finding the ID. Open SharePoint, and navigate to the list that contains your workflow. Click Edit this list, and then click List in the ribbon.

How to get id from array object in JavaScript?

The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned. If you want to find its index instead, use findIndex() : myArray.

Can you have a list of objects in Java?

Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.


1 Answers

That works for me as long as bars is a List

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

But if all you want is the id field it's a waste to pull entire domain class instances from the database. For now there's just the one field, but in practice it will likely be a larger table. So I'd use an HQL query:

def ids = Foo.executeQuery(
   'select f.id from Foo f where f.bar in (:bars)',
   [bars: bars])
like image 94
Burt Beckwith Avatar answered Sep 18 '22 15:09

Burt Beckwith