简体   繁体   中英

Grails / Hibernate criteria id inList

This question is based on the one I asked here . Same relationships and same goal. I have an instance of Thing. I want to get all instances of Foo that are associated with all instances of Bar that are associated with the instance of Thing that I have.

I have a method in my model that returns a list of objects based on some criteria.

class Foo {

    static List findAllAssociatedWith( Object obj ) {
        def results = null
        if( obj instanceof Bar) {
            results = Foo.withCriteria() {
                bars{
                    //inList( "id", Thing.bars.id ) // this does not work
                    inList( "id", [new Long(3), new Long(4)] ) // this works
                }
            }
        }
        return results
    }
}

Thing.bars.id returns the list of ids I want to check against, but apparently it is an an ArrayList of Integers even though Longs are expected. This is the error I get:

java.util.ArrayList cannot be cast to java.lang.Long. Stacktrace follows:
Message: java.util.ArrayList cannot be cast to java.lang.Long

Why is Thing.bars.id returning a list of Integers instead of a list of Longs and how do I fix it?

UPDATE:

I found the issue after calling println Things.bars.id . I expected it to return an ArrayList of numbers (Integers or Longs) like this:

[3,4]

but instead I got an ArrayList of ArrayLists where the first array list was what I wanted and the second array list was an empty list, like this:

[ [ 3, 4 ], [] ]

Not sure why Grails does this, but an easy way around it for now is Thing.bars.id.get( 0 )

ubiquibacon, you can flatten your array of arrays to simple array by using flatten method Thing.bars.id.flatten()

your [ [ 3, 4 ], [] ] turns into [3,4]

Without seeing the definition for Thing.bars , it's hard to tell what's going on here. However, if you have a list of Integers you'd like to turn into Longs, you can use

Thing.bars.id*.asType(Long)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM