HQL joins in Grails

2019-07-19 00:05发布

问题:

I have a relationship like this

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

class Bar {
    // Has nothing to tie it back to Foo or anything else of importance
}

class Thing {
    // Has nothing to tie it back to Foo or anything else of importance
}

I have an instance of Thing. I want to get all instances of Bar that are associated with all instances of Foo that are associated with the instance of Thing that I have.

I have used Grails executeQuery method several times but my query does not work.

Here is a working query that will get all instance of Foo related to an instance of Bar. I expect the query I need will look very similar, I'm just having trouble with the HQL joins.

SELECT DISTINCT f FROM Foo f INNER JOIN f.bars bars WHERE bars =:bars

回答1:

SELECT DISTINCT f.Bars FROM Foo f inner join f.things thing where thing.Id in (:validThingIds)

grails should support setting parameters and you basically need to pass the array of ids to the query.. The final part of the query should evaluate to (1,2,3,4) where 1,2,3,4 are the ids of the valid things.