Skip to content

Apply a requested join type without criteria or a sort - #17067

Merged
jdaugherty merged 31 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-07-requested-join-type
Nov 26, 2026
Merged

jdaugherty merged 31 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-07-requested-join-type

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Part 7 of the split of #16853, as agreed there and in the dev@ thread Fixes that change results on patch and minor branches. Relates to #15589.

Stacked on #17066. Until that merges, this pull request also shows the commits below it. Review the changes introduced by this part, including its review fixes, relative to #17066.

A where query, a detached criteria or a dynamic finder can request a
join type for an association, with fetch: [club: JoinType.INNER] or
join('club', JoinType.INNER). The type was only used when criteria or
a sort joined the association. Otherwise the association was fetched
with the outer join of its fetch mode, so
Team.where { ... }.list(fetch: [club: JoinType.INNER]) returned the
teams without a club, and the same query sorted by club.name did not.

A requested join type other than LEFT is now applied when the query is
executed, to list, get, find, count, the totalCount of a paged list, a
subquery and a query with a projection:

  • INNER and RIGHT on an association to a single instance join and
    fetch it; a right join is a right join, not an outer fetch;
  • a path that ends in a collection or passes through one restricts the
    query with a correlated subquery, so that the collection stays
    fetched with all of its elements, each instance is counted once, and
    the filters of the session, such as the tenant filter, apply;
  • every association on a requested path is joined and fetched;
  • a collection of a basic type is handled like any other collection;
  • a fetch mode requested afterwards replaces the join type, on the
    query and on the detached criteria, while the join that criteria on
    the association make keeps it.

Results that change

  • Requested INNER and RIGHT joins restrict list, get, find, count and totalCount even without association criteria or a sort. This includes nested paths, collections of entities or basic values, subqueries and property projections.
  • In an instance-returning query, a to-one RIGHT join retains one null for each unmatched associated instance, counted by count and totalCount, also when criteria on the association keep a right join that a later fetch mode replaced. This does not promise one null per unmatched row for projections: Hibernate 5 can deduplicate repeated projected values, including null.
  • A LEFT join requested for a nested path fetches its associations. With max or a positive offset, collections on that path load separately when accessed so pagination cannot leave them incomplete.
  • A sort through a path with a requested JoinType.LEFT, as in fetch: ['books.publisher': JoinType.LEFT] with sort: 'books.title' or sort: 'books.publisher.name', joins every association of the path with a left join, so it keeps the authors without books, also with grails.gorm.leftJoinAssociationSort off. A join type requested for books itself still decides how books is joined.
  • A paged query requesting a JoinType for a collection now pages root instances rather than joined rows: with enough matching instances, max: 2 can return two instances where the former page held only one. Plain join(association) and fetch: [association: 'join'] retain the old joined-row paging, which can return fewer instances and partially initialize a collection. JoinType.LEFT and the 'join' fetch mode therefore do not preserve the same page.
  • select() preserves a requested left join for existing criteria; a replacement fetch mode also applies to projections, which can now include null.
  • @Join applies its type on parameter-query data service methods. Dynamic-finder-named methods still use it only as a fetch mode; this limitation is now explicit in the guide and skill.
  • Where an ignored INNER request formerly kept extra root instances, remove the requested join type or use LEFT to retain that root selection. This does not restore the former collection pages described above. No compatibility setting: the old result ignored the request.

Release ordering and shared helpers

This part must ship with #17068, #17069 and #17071, after #17079 lands on 8.0.x. Those parts cover bulk operations, criteria builders and static-list/example paths respectively.

The superseded-join getter is read across package/module boundaries by DynamicFinder and HibernateCriteriaBuilder to retain criteria-join semantics when a later fetch mode replaces a requested type. It is marked @Internal. The two GrailsHibernateUtil helpers are shared with the criteria-builder implementation in #17069; keeping one implementation avoids divergent join and fetch rules across the same-release changes. Tests now verify replacement and cloning through returned rows and counts rather than asserting the internal map.

Verification

At de762c0 the full Hibernate 5 core suite (1,177 cases, zero failures, 55 skipped) and the datamapping-core suite (252 cases, 1 skipped) pass, with codeStyle of both modules. At 4301e58 RAT and the guide build passed as well. Thirteen targeted pagination/right-join regression cases failed before the fix and pass after it, and the features for an alias named like an association and for a right join that a fetch mode replaced failed before de762c0.

Contributor Checklist

Please review the following checklist before submitting your pull request. Pull requests that do not meet these requirements may be closed without review.

Issue and Scope

  • This PR is linked to an existing issue that has been acknowledged or approved by the project team. If no approved issue exists, please give background on why this change is necessary. Tickets are preferred for release change log history.
  • This PR addresses the complete scope of the linked issue. Partial implementations or unfinished work should not be submitted for review.
  • This PR contains a single, focused change. Unrelated changes should be submitted as separate pull requests.
  • This PR targets the correct branch for the type of change:
    • Patch release branches (e.g., 7.0.x): Bug fixes only. No new features or API changes.
    • Minor release branches (e.g., 7.1.x): New features are welcome, but breaking existing APIs must be avoided.
    • Major release branches (e.g., 8.0.x): Reserved for major changes. Breaking API changes are permitted.

Code Quality

  • I have added or updated tests that cover the changes introduced in this PR. All code contributions are expected to include appropriate test coverage.
  • I have verified that all existing tests pass by running ./gradlew build --rerun-tasks.
  • My code follows the project's code style guidelines. I have run ./gradlew codeStyle and resolved any violations. See Code Style for details.
  • This PR does not include mass reformatting, style-only changes, or large-scale refactoring unless it was explicitly approved in the linked issue. Unsolicited reformatting will not be accepted.
  • If generative AI tooling was used in preparing this contribution, a quality model was used to ensure contributions are consistent with the project's quality standards.

Licensing and Attribution

Documentation

  • If this PR introduces user-facing changes, I have included or updated the relevant documentation.
  • If this PR adds a new feature, I have updated the What's New section of the Grails Guide.
  • If this PR introduces breaking changes or changes that require user action during an upgrade, I have updated the Upgrade Notes for the corresponding version in the Grails Guide.
  • The PR description clearly explains what was changed and why.

First-time contributors: Please read our Contributing Guide before submitting.
Pull requests that appear to be auto-generated, incomplete, or unrelated to an approved issue may be
closed to help maintainers focus on reviewed and planned work. We appreciate your understanding.

matrei and others added 11 commits November 19, 2026 09:30
Sorting a where query by a property of an association, such as
sort: 'club.name', failed with a QueryException when the query also
had criteria on that association. The criteria join the association
under a generated alias, and the order was added with the association
path, which Hibernate cannot resolve. The order now uses the alias of
the join.
A sort by a path through more than one association, such as
owner.employer.name, is still not supported.
A sort by a path that crosses more than one association, such as
team.club.name, failed with a QueryException whether or not the where
query joined the nested association, because order() split the path at
its first dot only. The sort property is now qualified with the alias of
the last association on its path: an association the query has already
joined is reused, and one it has not joined yet is joined for the sort
and registered like any other join. A sort by two properties of the same
association no longer fails with "duplicate association path" either,
since the sort join is registered instead of created anew for every
order.
Since order() walks the whole sort path, a sort by the identifier of an
association that follows another one on the path, such as team.club.id,
joined that last association too. The join is an inner join unless fetch
requests another type, so the sort left out the rows where the
association is null. Before, only the first association was joined and
Hibernate read club.id from the foreign key of team, which kept them.

The identifier is sorted by the foreign key again when the entity before
the association holds it. An association without such a foreign key, a
hasOne or the inverse side of a one-to-one, is still joined, and so is
the first association of a path, as it always has been.

The spec also covers the join type of a sort join: an inner join by
default, and a left join when fetch requests one. Team.club is nullable
in the fixture for these cases. The docs describe the inner join, how to
request a left join, and the identifier of a nested association.
list with a map of sort properties, such as
Team.list(sort: ['club.name': 'asc', name: 'desc']), sorted by the last
entry only, because each entry replaced the orders of the query. The
same held for a default sort that the mapping declares for more than
one property. Every entry is now applied, in the order of the map.

An association is joined once for all the sort properties that use it.
list joined it once for each, and find and findAll with an example,
findWhere and findAllWhere failed with "duplicate association path".

Part 2 of the split of apache#16853.
A paged query of a detached criteria that has an alias for the queried
class, and criteria that use it, failed when totalCount was read:

    new DetachedCriteria(Team, 't').eq('t.name', 'Arsenal').list(max: 2).totalCount

The count runs on a copy of the criteria, and the copy was created
without the alias, so Hibernate could not resolve t.name. The copy now
has the alias of the original.

Part 3 of the split of apache#16853.
count on a where query or a detached criteria that has a sort, such as
Team.where { ... }.sort('name').count(), kept the order by in the query
that counts the rows, which H2 rejects with "must be in the GROUP BY
list". A query that only counts its rows now has no orders.

The join that a sort by a property of an association makes is kept, so
the count is that of the rows which list returns for the same query.

Part 4 of the split of apache#16853.
… by it

A sort by a property of an association joins the association with an
inner join, so it leaves out the instances whose association is null:
Team.list(sort: 'club.name') does not return the teams without a club,
and count and the totalCount of a paged list do not count them.

The new grails.gorm.leftJoinAssociationSort setting makes an association
that is joined only for a sort a left join, in where queries, detached
criteria, dynamic finders, list, find and findAll with an example,
findWhere, findAllWhere and a criteria query that is passed pagination
arguments. It is disabled by default, so the results of existing
applications do not change in a patch release. Grails 8.1 enables it by
default.

With the setting, a sort by a nested identifier, such as team.club.id,
goes through the left join. Without it, it is still read from the
foreign key.

A sort by a property of a collection keeps its inner join: Hibernate
fetches a collection through a left join, which is handled separately.

Part 5 of the split of apache#16853.
A where query, a detached criteria and a dynamic finder joined an
association as soon as criteria, a projection or a sort needed it. The
rest of the query can still change after that: criteria passed to list
are added later, and the fetch argument of list, which can request a
join type, is read last. The result depended on the order in which the
query was put together:

- a join type in the fetch argument of list was not used for the join
  that the criteria or a projection had already made;
- a sort stored on the query with sort() was joined before a join type
  requested in list was known, and criteria passed to list could not
  join the same association through an alias;
- a join type was looked up by the name of the association, so a type
  requested for club was used for team.club, and one requested for
  team.club was not;
- criteria on a nested association used twice failed with
  "duplicate association path".

Criteria, projections and orders only need the alias of a join. A join
is now registered under its path from the root entity and its alias,
and made when the query is executed, or when a subquery is handed to
the query that embeds it, with the join type that the query requests
for that path. A listener of the query events that adds criteria on an
association to find and findAll with an example, findWhere or
findAllWhere gets its joins made after the event.

Part 6 of the split of apache#16853.
A where query, a detached criteria or a dynamic finder can request a
join type for an association, with fetch: [club: JoinType.INNER] or
join('club', JoinType.INNER). The type was only used when criteria or
a sort joined the association. Otherwise the association was fetched
with the outer join of its fetch mode, so
Team.where { ... }.list(fetch: [club: JoinType.INNER]) returned the
teams without a club, and the same query sorted by club.name did not.

A requested join type other than LEFT is now applied when the query is
executed, to list, get, find, count, the totalCount of a paged list, a
subquery and a query with a projection:

- INNER and RIGHT on an association to a single instance join and
  fetch it; a right join is a right join, not an outer fetch;
- a path that ends in a collection or passes through one restricts the
  query with a correlated subquery, so that the collection stays
  fetched with all of its elements, each instance is counted once, and
  the filters of the session, such as the tenant filter, apply;
- every association on a requested path is joined and fetched;
- a collection of a basic type is handled like any other collection;
- a fetch mode requested afterwards replaces the join type, on the
  query and on the detached criteria, while the join that criteria on
  the association make keeps it.

Part 7 of the split of apache#16853.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. An inner join with no criteria and no sort still keeps a row that has no child.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 1814db6 (base 7.0.x): 7fc46a7 and the merge of #17064, which leaves the diff of 7fc46a7 as it was. I probed where queries, detached criteria, finders, data services, subqueries and bulk updates that request a join type:

  • at this head, at #17066 (7786cbc), on 7.0.x (aee4c04) and at the stack top (16bd465), with the setting off and on;
  • with Hibernate 7 on 8.0.x (0518f48) and at #17079 (6de9334);
  • with a team without a club, a team without players, a team with three players of which one has no contract, and clubs that no team refers to.

The setting changes none of these results, and #17066 returns what 7.0.x returns for all of them. This part changes these:

7.0.x and #17066 This head Hibernate 7 on 8.0.x #17079
Team.where { name ==~ '%First%' }.list(fetch: [club: JoinType.INNER]), also join('club', JoinType.INNER), findAllByNameLike('%First%', [fetch: …]) and findAll(fetch: …) { … } 5 teams 4 4 4
the same with count(), the totalCount of max: 2, projections { count() } and property('name') 5 4 5 4
Team.where { name == 'Unattached First Team' }.join('club', JoinType.INNER).get(), also find(fetch: …) the team null null null
fetch: [players: JoinType.INNER], also JoinType.RIGHT 5 4 4 4
the same with count() and totalCount 5 4 5 4
Player.where { … }.join('team.club', JoinType.INNER).list(), also count() and totalCount 7 players 6 7 6
Team.where { name ==~ '%Team%' }.list(fetch: ['players.contract': JoinType.INNER], max: 3).totalCount 7 5 7 5
a subquery, as in new DetachedCriteria(Team).inList('id', Team.where { … }.join('club', JoinType.INNER).id()) 5 4 5 4

So I agree that this needs no setting, by #17061: the old result ignores a join type that the call requests. For the list of a where query, Hibernate 7 on 8.0.x already returns the new rows, while its count and totalCount don't, which #17079 fixes. Apart from points 1, 2 and 6, and the projections that #17079 lists as different, this head returns what #17079 returns.

Needs a fix

1. A page of a query that requests a join type for a path through a collection holds collections without all of their elements. This head fetches the collection on such a path, such as players for fetch: ['players.contract': JoinType.INNER]. With max, Hibernate 5 limits the rows of the join, so a collection on the page holds only the elements in those rows:

Team.where { name ==~ '%Team%' }.list(fetch: ['players.contract': JoinType.INNER], max: 2, sort: 'name', order: 'desc') 7.0.x This head #17079
players of the team with three players not fetched, 3 players when loaded fetched, with 1 of its 3 players fetched, with its 3 players

The same happens with:

  • JoinType.LEFT;
  • max with offset;
  • a detached criteria with join('players.contract', JoinType.INNER);
  • Player.where { … }.list(fetch: ['team.players': JoinType.LEFT], max: 2, sort: 'name', order: 'desc'): the team with three players holds 1 of them.

The note says that a join type "never leaves elements out of a fetched collection". A fetch of the collection itself, as in fetch: [players: JoinType.LEFT] with max, already does this on 7.0.x, where Hibernate 7 on 8.0.x fetches all 3 players. These paths didn't fetch the collection on 7.0.x, though. Not fetching a collection on the path of a paged query keeps the result of 7.0.x.

2. A right join returns one null for all the clubs that no team refers to, and counts each of them. With two such clubs, new DetachedCriteria(Team).join('club', JoinType.RIGHT) returns:

This head Hibernate 7 on 8.0.x #17079
list() 3 teams and one null 3 teams and two null 3 teams and two null
count(), and the totalCount of max: 10 5 4 5

So count doesn't return the number of rows that list returns, which the note of #17064 says it does, and Hibernate 5 and Hibernate 7 return different lists after the merge-up. The note describes the single null. A null for each row, as Hibernate 7 returns it, would make list, count and both modules agree.

3. "Results that change" lists only the inner join for list, get, find, count and totalCount. The note has more, and the description should list it too:

  • a right join;
  • a subquery and a property projection;
  • a path through more than one association, and a path through a collection;
  • a left join for a path, which now fetches the associations on it;
  • a collection of a basic type;
  • a data service method with @Join (point 4).

Two changes are in neither:

  • Team.where { club.name == 'Chelsea' || name == 'Unattached First Team' }.join('club', JoinType.LEFT).select('club').list() returned 1 team on 7.0.x and returns 2 here, as at #17079. The left join is now kept for the criteria after select. The persistence guide describes it, but no note says that it changed.
  • Team.where { name ==~ '%First%' }.property('club.name').join('club', JoinType.INNER).join('club').list() returned 3 values on 7.0.x and returns 4 here, with null. The fetch mode now replaces the inner join for the projection too. Hibernate 7 leaves the null out, as it does for every projection of a property of an association (note 8 on #17066).

4. @Join on a data service. The note says that a data service method that queries by its parameters, such as Book find(String title), applies the join type of @Join(value = 'author', type = JoinType.INNER). The skill entry says to search for @Join, and that each of these queries now applies the join type. It holds for such a method. With @Join(value = 'club', type = JoinType.INNER), Team find(String name) returns null here for the team without a club, List<Team> listTeams(String name) returns nothing and Number count(String name) returns 0. On 7.0.x they returned the team, and 1.

A method named like a dynamic finder doesn't apply it. findByName, findAllByNameLike and countByNameLike with @Join(value = 'club', type = JoinType.INNER) still return the team without a club, at this head, at the stack top and at #17079. FindAllByImplementer.buildArgs passes fetch: [club: 'join'] and drops the type. Either the note and the skill entry say that such a method doesn't apply the type, or the implementer passes it on, here and in #17079.

5. New public API on 7.0.x. This part adds:

  • AbstractDetachedCriteria.getSupersededJoinTypes(), with a protected field, on every detached criteria of every datastore;
  • the public static GrailsHibernateUtil.fetchAssociationsBefore and joinedInSubquery.

The Hibernate skill asks for no new public or protected methods on 7.0.x and 8.0.x. Only AbstractHibernateQuery calls the two helpers, so they can be private there. DynamicFinder and HibernateCriteriaBuilder read the getter. If it has to stay public, the description should say why. DetachedCriteriaJoinTypeSpec tests that map, not what a query returns (rule 9 of AGENTS.md, "Test via public APIs").

6. This part should merge together with #17068, #17069 and #17071. #17079 makes all four changes for Hibernate 7.

Without #17068, updateAll and deleteAll change rows that list of the same query leaves out:

This head Stack top and #17079
Team.where { name ==~ '%First%' }.join('club', JoinType.INNER).updateAll(name: 'Renamed'), whose list has 4 teams 5 updated 4
the same with join('players', JoinType.INNER) 5 4
Team.where { name == 'Empty Team' || name == 'Playerless First Team' }.join('club', JoinType.INNER).deleteAll(), one of them without a club 2 deleted 1

Without #17071, these keep the rows of 7.0.x here, while the stack top and #17079 apply the join type:

  • Team.list(fetch: [club: JoinType.INNER]): 7 teams, against 5;
  • Player.list(fetch: ['team.club': JoinType.INNER]): 7 players, against 6;
  • findAllWhere([name: 'Unattached First Team'], [fetch: [club: JoinType.INNER]]): the team, against nothing.

The description says that this merges once #17079 is on 8.0.x. It should also say that the three parts merge with it, into the same release. Otherwise the Hibernate 5 module of 8.0.x differs from Hibernate 7 after the merge-up.

7. The pull request conflicts with 7.0.x, and needs run ci, as on #17066. Locally, the tests pass at this head: grails-data-hibernate5-core has 1052 tests, 55 skipped, and grails-datamapping-core has 257 tests, 1 skipped. The guide builds, and the note's list renders as a list.

Notes

  1. On James's comment, I agree with your reply. Team.list(fetch: [club: JoinType.INNER]) returns 7 teams here. At the stack top it returns 5, as at #17079.

  2. The imports of AssociationSortSpec and WhereQueryWithAssociationSortSpec are reordered again, which has nothing to do with the fix.

  3. DetachedCriteriaJoinTypeSpec uses double-quoted feature names and def for locals. New features take single quotes and final.

  4. As a fix that changes a result, this needs a second reviewer (#17061).

Keep join lookup private to its only caller. Document changed page contents and collection duplicates, and cover sorting before pagination. Preserve both sets of upgrade notes when merging the release branch.
Keep the count-projection and listener-order regressions, import RowCountProjection, and remove upgrade entries for calls that previously failed. Counts preserve joined rows rather than promising a distinct entity total.
@github-actions
github-actions Bot dismissed matrei’s stale review November 25, 2026 13:44

Dismissed automatically: the pull request changed after this approval, from f9362bd to 4301e58.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. An alias named like an association hides an inner join the call asked for.

matrei
matrei previously approved these changes Nov 25, 2026

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fourth round, at 4301e58. It merges #17066's 9c69ff2, which this part lacked in round 3, and adds a fix: a sort through a path below a requested JoinType.LEFT keeps the associations of that path outer, with the setting off and on. Apart from the fix, the tree is that of my own merge of f9362bd and 9c69ff2. The push dismissed my approval.

I ran the fix with the domain of my earlier probes at this head and at f9362bd, on 7.0.x (28f27fe), and with Hibernate 7 on 8.0.x (99aedeb) and at #17079 (053255f). The two teams without players are Playerless First Team and Empty Team:

7.0.x f9362bd This head, setting off and on Hibernate 7
Team.where { name ==~ '%' }.list(fetch: ['players.contract': JoinType.LEFT], sort: 'players.name') 5 teams, without those two 5 teams all 7 all 7
The same with sort: 'players.contract.salary', also as a detached criteria, as findAllByNameLike, and with sort() before list throws QueryException 5 teams all 7 all 7
A player without a team, in Player.where { name ==~ '%' }.list(fetch: ['team.club': JoinType.LEFT], sort: 'team.name') left out left out with the setting off kept kept
The same with sort: 'team.club.name', and with fetch: ['team.players': JoinType.LEFT], sort: 'team.players.name' throws QueryException left out with the setting off kept kept

The Hibernate 7 column is the same on 8.0.x and at #17079, with the setting off and on. What stays as it was:

  • A join type requested for the middle association still decides its join. fetch: [players: JoinType.INNER, 'players.contract': JoinType.LEFT] returns the 5 teams with players, as with Hibernate 7.
  • fetch: ['players.contract': JoinType.INNER], and the same sort without a join type, return those 5 teams too.
  • fetch: [players: 'select', 'players.contract': JoinType.LEFT] keeps all 7 teams, as #17079 does.
  • With the setting off, a sort by another association, sort: 'club.name', still leaves out the teams without a club.
  • On a page, as with max: 1 for Squad Team, the players aren't loaded with the query, and they hold all 3 when accessed.
  • join('players.contract', JoinType.LEFT).count() counts all 7 teams.

list(max: 10) of the first row lists the 7 teams and gives a totalCount of 9, the joined rows. That's the old count of a where query sorted by a collection, which I describe in my review of #17070.

The grails-data-hibernate5-core tests pass with this fix at #17070's new head (1555 tests, 60 skipped), and the guide builds. CI passed with the tests, apart from Redis Tests (25, 7.4). There MemoizeObjectAnnotationSpec failed with a SocketTimeoutException from Jedis, which is unrelated, and it passed on a rerun.

Description

"Results that change" doesn't list the new result yet. On 7.0.x, fetch: ['players.contract': JoinType.LEFT], sort: 'players.name' returns 5 teams, and a sort by team.name with fetch: ['team.club': JoinType.LEFT] leaves out a player without a team. Both now keep them. Maybe a bullet:

  • A sort through a path with a requested JoinType.LEFT, as in fetch: ['books.publisher': JoinType.LEFT] with sort: 'books.title' or sort: 'books.publisher.name', joins every association of the path with a left join, so it keeps the authors without books, also with grails.gorm.leftJoinAssociationSort off. A join type requested for books itself still decides how books is joined.

A description isn't part of the tree, so the edit won't dismiss this approval.

Optional

In the note and the skill entry, "Explicit intermediate join types, replacement fetch modes and association criteria keep their existing precedence" can be read as fetch: [books: 'select'] making the sort an inner join again, which it doesn't. What the spec shows is narrower. A join type requested for books decides, also when a fetch mode replaces it later. A later join('books.publisher') replaces the left join of the path. Criteria on books keep their inner join. Maybe:

A join type requested for books itself, also when a fetch mode replaces it later, and criteria on books still decide how books is joined.

As a fix that changes a result, this needs a second approval under #17061.

@borinquenkid borinquenkid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things before I approve.

  1. An alias with an association's name swallows the requested join. getOrRegisterJoinAt looks up createdAssociationPaths, which registerJoin keys by path and by alias. After createAlias('players', 'club'), a request for club finds the players join, and the inner join on club is never made. Suggested fix: reuse the entry only when join.associationPath.equals(associationPath), plus a spec with that alias.

  2. fetching.adoc line 125 says the list contains null once for all right-join rows with no instance. Reading the code, I expect one null per such row. Could you check which it is and adjust the sentence or the code?

Both come from reading the code, not from a run.

@sbglasius sbglasius left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an AI assisted review

Reviewed relative to #17066. The approach looks right and the upgrade notes are thorough. A few points:

  1. AbstractHibernateQuery.java:1163 – keepNullRows is true for any requested RIGHT, even one that is turned into an inner join (collection) or skipped (path that isn't an association). The query then still switches to ROOT_ENTITY and deduplicates by identity. So a RIGHT request on one collection also removes the duplicate rows that a join('books') on the same query used to return. Could this check only to-one RIGHT joins that were actually made?
  2. AbstractHibernateQuery.java:632 – using sqlRestriction("1=1") as a with-clause to stop Hibernate fetching the collection relies on undocumented Hibernate behaviour. Please add a test that fails if a Hibernate upgrade starts fetching that join again (an incomplete collection after a paged query).
  3. AbstractDetachedCriteria.getSupersededJoinTypes() adds new public API on 7.0.x. If it's only for DynamicFinder and HibernateCriteriaBuilder, consider marking it @Internal.
  4. jamesfredley's thread on aliases (an alias named like the association, AbstractHibernateQuery) has no reply yet. Please answer it before merging.

getHibernateCriteria() makes the joins and adds the orders that the
query has registered so far, with the join types that it requests at
that point. The paged list and the pre-query event of a query by
example rely on that. Its Javadoc now says so.
A join was registered under its association path and its alias in one
map, so an alias named like an association, as in
createAlias('players', 'club'), stood for the join of that association.
A join type requested for club was then given to the join of the
players, and the inner join of club was never made. An alias named
like a collection made the collection look joined, so the query was
not restricted to the instances that have elements. Joins are now
looked up by their path in a map of their own, and an alias keeps
standing for its own join, as it does for Hibernate.

A query keeps a row without an instance for each row of a right join
only when it made a right join of an association to a single instance,
not whenever a right join is requested. A right join that criteria on
the association still make after a fetch mode replaced it returned a
single null for all such rows, while count counted each of them.

getSupersededJoinTypes is marked as internal, and the fetching guide
says that a right join returns a null for each such row, as the upgrade
note does. AssociationSortSpec covers a sort by the identifier of a
nested association that a query requests an inner join for.
@github-actions
github-actions Bot dismissed matrei’s stale review November 25, 2026 22:09

Dismissed automatically: the pull request changed after this approval, from 4301e58 to de762c0.

@jdaugherty

Copy link
Copy Markdown
Contributor Author

@borinquenkid

  1. The alias: fixed in de762c0, see my reply on James's thread.
  2. fetching.adoc: it's one null per row. The code keeps every null row, and "a right join keeps one null row for each club that no team refers to" asserts two for two such clubs. The sentence now says so, as the upgrade note and the skill already did.

From your review of #17066: AssociationSortSpec now sorts by team.club.id with an inner join requested for team.club, as a where query with sort() and with list(sort:), a detached criteria, a dynamic finder, and the totalCount of a paged list. Each leaves out the player whose team has no club, with the setting off and on.

@sbglasius

  1. A row without an instance is now kept only when the query made a right join of an association to a single instance, not whenever RIGHT is requested. Through list the rows were already made distinct by identity, so the duplicates of join('books') weren't affected. One case was: a right join that criteria on the association still make after a fetch mode replaced it, as in Team.where { club.name ==~ '%' }.join('club', JoinType.RIGHT).join('club'), returned a single null while count counted each row. It now returns one per row, and AssociationJoinTypeSpec has a feature for it, which failed before.
  2. "a paged #api nested LEFT sort keeps the complete collection at offset #offset" in NestedRequestedLeftJoinSpec is that test. It pages to one root whose collection has three elements, and asserts that the collection isn't initialized and holds all three. Without the sqlRestriction("1=1") with-clause, all 12 of its cases fail, with the setting off and on: Hibernate fetches the collection through the paged join, and it holds one of the three elements.
  3. getSupersededJoinTypes() is now @Internal, and its Javadoc says that it's for the datastore implementations.
  4. Answered on James's thread, with the fix.

The full grails-data-hibernate5-core suite (1177 tests, 55 skipped) and the grails-datamapping-core suite (252 tests, 1 skipped) pass at de762c0, with codeStyle.

@testlens-app

testlens-app Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🚨 All tests passed but jobs failed 🚨

Failed Jobs without Test Failures

❌ CI / Spring Security Tests (25)

🏷️ Commit: de762c0
▶️ Tests: 59777 executed
⚪️ Checks: 58/58 completed

Rerun Controls

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

@borinquenkid borinquenkid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved at de762c0. Joins are now looked up by path in their own map, so an alias named like an association no longer takes over that association's join, and the new AssociationJoinTypeSpec feature covers both directions. The fetching.adoc sentence now matches the code. The team.club.id rows in AssociationSortSpec close the case from my #17066 review.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fifth round, at de762c0. Since my fourth review, f236529 merges #17066's Javadoc commit, 52c33eb, which 7.0.x already has, and de762c0 fixes the alias that James and borinquenkid reported. It also keeps a row without an instance only once the query has made a right join of an association to a single instance. It marks getSupersededJoinTypes() @Internal, corrects the sentence in fetching.adoc, and adds the team.club.id rows to AssociationSortSpec. The push dismissed my approval. The branch merges cleanly with 7.0.x at 0c81611.

James's comment of 11-25 held, and it's fixed, with the setting off and on:

7.0.x (0c81611) 4301e58 This head Hibernate 7 at #17079 (eed6c6e)
new DetachedCriteria(Team).build { createAlias('players', 'club') }.join('club', JoinType.INNER).list(), also as a where query, with max: 10, with the join before the build, with JoinType.RIGHT, and as Team.where { name ==~ '%' }.list(fetch: [club: JoinType.INNER]) { createAlias('players', 'club') } 5 teams, with Unattached First Team the same the 4 teams with players and a club the 4 teams
build { createAlias('club', 'players') }.join('players', JoinType.INNER) 5 teams, with Playerless First Team the same the 4 teams the 4 teams

An alias with another name, the criteria and the sort through the alias named club, and JoinType.LEFT for the association give what they gave at 4301e58. count() and the totalCount of a page give 6 for the first row, a row for each player of those teams, as Hibernate 7 does. That's the count of #17178 for a join through a collection, not this fix's. From #17069 on, the criteria query Team.createCriteria().list { createAlias('players', 'club'); join('club', JoinType.INNER) } leaves Unattached First Team out too.

The rows without an instance now follow count. With two clubs that no team refers to, Team.where { club.name ==~ '%' }.join('club', JoinType.RIGHT).join('club').list() returns the 5 teams with a club and two nulls, also with max: 10, as Hibernate 7 at #17079 does. At 4301e58 it returned one null, and count() gave 7. A right join of a collection, also with join('club'), with a right join of the club or with a projection, gives what it gave at 4301e58.

I checked jdaugherty's answer on the with-clause too. Without sqlRestriction("1=1"), the 12 paged cases of NestedRequestedLeftJoinSpec and NestedRequestedLeftJoinEnabledSpec fail, and with it they pass.

Description

My point of the fourth round is still open. "Results that change" doesn't list the sort through a path with a requested JoinType.LEFT, which changes what 7.0.x returns: fetch: ['players.contract': JoinType.LEFT], sort: 'players.name' returns 5 teams there, and all 7 here. The bullet I suggested would do:

  • A sort through a path with a requested JoinType.LEFT, as in fetch: ['books.publisher': JoinType.LEFT] with sort: 'books.title' or sort: 'books.publisher.name', joins every association of the path with a left join, so it keeps the authors without books, also with grails.gorm.leftJoinAssociationSort off. A join type requested for books itself still decides how books is joined.

A description isn't part of the tree, so the edit won't dismiss this approval.

What I ran

  • My probes of the earlier rounds: apart from the rows above, they give the same results as at 4301e58, with the setting off and on.
  • The tests: the grails-data-hibernate5-core tests pass at this head (1182 tests, 60 skipped), and so do the grails-datamapping-core tests (252 tests, 1 skipped). The guide builds.

CI passed with the tests, apart from Spring Security Tests (25). That job failed before it ran a test, because Gradle couldn't resolve the com.gradle.develocity 4.5.1 plugin for build-logic. It needs a rerun.

borinquenkid approved this head, so with this review it has the two approvals that #17061 asks for a fix that changes a result.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. A listener that asks for the criteria before joining club as a left join still leaves that team out.

* @return The hibernate criteria
*/
public Criteria getHibernateCriteria() {
applyDeferredJoins();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A where query should include Chelsea First Team and Unattached First Team. A listener asks for the criteria, then joins club as a left join. Only Chelsea First Team is returned, because the first ask joins club as an inner join and the left join does not replace it. Keep the left join.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of scope for this part, and not a supported use of a query listener. A listener can restrict the query, as the tenant listener does with its criteria, but it isn't meant to redefine it: the join types are the caller's. getHibernateCriteria() makes the joins with the join types requested at that point, as its Javadoc says. That came with #17066 and is already on 7.0.x. A join type requested afterwards for an association that's already joined doesn't change the join, on 7.0.x too. Before #17066 the join was made as soon as the criteria were added, so a listener's join type never replaced it either.

@jdaugherty

Copy link
Copy Markdown
Contributor Author

Given that Walter & Mattias have approved this and James Fredley's comments are out of scope of this PR's target, I'm going to merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants