apache / apache/grails-core

How to use join on nested association?

Open
#14,422 0 comments 0 reactions 0 assignees View on GitHub
relates-to: grails-data-hibernate5
Dominant language
Groovy
Stars
2.9k
Forks
975
Avg merge
1d 22h
Merged PRs (30d)
92

Description

I have a complex structure which I'll simplify for this example:

```
class Site {
...
}

class Series {
Site primarySite
Set additionalSites
...
}

class Story {
Series series
...
}
```

I need to select all stories associated with a Site and make further more detailed selections with that.

First I select all series and that works fine using this:

```
def siteSeriesCriteria() {
return Series.where {
join("additionalSites", JoinType.LEFT)
or {
eq('primarySite', thisSite)
additionalSites {
eq('id', thisSite.id)
}
}
}
}

list = siteSeriesCriteria().id().list()
```
That produces the intended SQL:

```
select
this_.id as y0_
from
series this_
left outer join series_site additional3_ on
this_.id = additional3_.series_additional_sites_id
left outer join site additional1_ on
additional3_.site_id = additional1_.id
where
(this_.primary_site_id =?
or (additional1_.id =?))
```

But when I try to use the deeper nested level that doesn't work anymore:

```
def siteStoryCriteria() {
return Story.where {
series in siteSeriesCriteria().id()
}
}
list = siteStoryCriteria().id().list()
```

Now the join is no longer a left outer:
```
select
this_.id as y0_
from
story this_
where
this_.series_id in (
select
this_.id as y0_
from
series this_
inner join series_site additional3_ on
this_.id = additional3_.series_additional_sites_id
inner join site additional1_ on
additional3_.site_id = additional1_.id
where
(this_.primary_site_id =?
or (additional1_.id =?)))
```

I've read that join() only works on the tree root of the Criteria-tree. But how am I supposed to solve this?

I've tried to add
join("series.additionalSites", JoinType.LEFT)
to the nested criteria, but that doesn't work either. I'm stumped here...

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the Series.where and Story.where criteria shown in the issue, including the generated SQL for the nested association query. Trace how join("additionalSites", JoinType.LEFT) is applied inside siteSeriesCriteria and determine whether a supported nested-criteria approach can preserve the left outer join; done means a documented or tested approach produces the intended story results.

Written by the indexing model from the issue text.

Assessment

Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.