Skip to content

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

Open
jdaugherty wants to merge 28 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-07-requested-join-type
Open

jdaugherty wants to merge 28 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. 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 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. 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 4301e58 the full Hibernate 5 core suite passes (1,168 cases, zero failures, 60 skipped), together with the datamapping-core suite, full codeStyle, RAT and guide build. Thirteen targeted pagination/right-join regression cases failed before the fix and pass after it.

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.

for (Object o : fetch.keySet()) {
String associationName = (String) o;

final FetchMode fetchMode = getFetchMode(fetch.get(associationName));

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.

Team.list(fetch: [club: JoinType.INNER]) should leave out a team with no club. The team stays, because the inner join is read as a fetch mode and no join is made. Make the join the call asked for.

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.

Team.list(fetch: [club: JoinType.INNER]) is the static-list path addressed by part 11, #17071. This part covers where queries, detached criteria and dynamic finders; it does not change static list or query-by-example.

Please target this finding to #17071 rather than adding the static-list implementation here. Both pieces remain subject to the same merge ordering agreed on dev@: the Hibernate 7 rule and spec in #17079 must land on 8.0.x before the requested-join parts merge into 7.0.x.

@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.
Warn once at datastore startup for an explicitly false compatibility setting and cover unset, true and false. Rename the settings page, repair its links and list defaults separately for each release line. Carry the reviewed parent changes forward.
Document stored sorts using the requested fetch join type and repair the rendered list. Remove the one-caller association helper and unrelated import churn while merging the reviewed parent.
Load collections on paged requested-join paths separately, preserving complete contents. Retain each unmatched right-join row while deduplicating real entities. Exercise these results and cloned fetch replacements through public queries, and clarify the data-service limitation and changed results.

@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 again at 56639c2. Most points from my first review are fixed:

  1. A paged query no longer leaves elements out of a collection on a requested path. The collections on the path are loaded when accessed, with all of their elements. With fetch: ['players.contract': JoinType.INNER] or ['team.players': JoinType.LEFT], with max and with offset, the team with three players holds all three, and these queries return what they return on 7.0.x.
  2. A right join returns a null for each club that no team refers to, and count and totalCount match list, as with Hibernate 7.
  3. "Results that change" lists the other changes, including the two from my first review.
  4. The note and the skill entry say that a data service method named like a dynamic finder doesn't apply the join type of @Join.
  5. The description says why the getter and the two helpers are public, and a feature that tests a copy through what the query returns replaces DetachedCriteriaJoinTypeSpec. I'm fine with that.
  6. "Release ordering" says that this part ships with #17068, #17069 and #17071.
  7. The pull request merges cleanly with 7.0.x and has run ci, and CI passed with the tests.

My other probes give the same results here as at 1814db6, with the setting off and on. #17079 (1cba001) returns what it returned at 6de9334. The tests of grails-data-hibernate5-core (1086 tests, 60 skipped) and grails-datamapping-core (252 tests, 1 skipped) pass here, and the note's list renders as a list.

Needs a fix

A paged query that requests a join type for a collection now returns another page, and no note says so. On 7.0.x, the page of such a query was a page of joined rows, so it could hold fewer instances than max. Here it holds max instances:

Team.where { name in ['Squad Team', 'Unattached First Team'] }.list(fetch: [players: JoinType.LEFT], max: 2, sort: 'name') 7.0.x and #17066 This head Hibernate 7, on 8.0.x and at #17079
teams on the page 1, Squad Team 2 2
players of Squad Team fetched, 2 of its 3 loaded when accessed, all 3 fetched, all 3

The same goes for JoinType.INNER, and for join('players', JoinType.LEFT) on a detached criteria. totalCount is 2 on all of them. The new page is right, and it's what Hibernate 7 returns. The note only says that the collections on the path are loaded separately, though.

A fetch mode keeps the old page. fetch: [players: 'join'] and join('players') with max: 2 still return Squad Team alone, with 2 of its 3 players, here as on 7.0.x. Hibernate 7 returns both teams with all their players. The note says to request JoinType.LEFT or 'join' to return the instances as before, but in a paged query the two now give different pages.

The note and "Results that change" could say that a paged query with a join type for a collection now returns max instances, and that 'join' still pages the joined rows. The page of 'join' is the same on 7.0.x, so changing it is for an issue of its own, as a Hibernate 5 result to bring in line with Hibernate 7.

Smaller points

  • WhereQueryWithAssociationSortSpec imports spock.lang.IgnoreIf and spock.lang.Requires twice: after grails.gorm.DetachedCriteria, and again further down. The merge kept the two lines that #17066 removed.
  • new DetachedCriteria(Team).join('club', JoinType.RIGHT).property('name').list() returns one null for the two clubs that no team refers to, while count() counts both, and Hibernate 7 returns two. Hibernate 5 returns a repeated value of a projection once when the query joins, on 7.0.x too: Team.where { name ==~ '%First%' }.join('club', JoinType.INNER).property('club.name').list() returns Arsenal once for its two teams. So it needn't hold this part, but the note's "list keeps one null per such row" holds for instances, not for a projection.

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

@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 the call asked for still keeps a team with no club when there is no other restriction.

for (Object o : fetch.keySet()) {
String associationName = (String) o;

final FetchMode fetchMode = getFetchMode(fetch.get(associationName));

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.

Team.list(fetch: [club: JoinType.INNER]) should leave out Unattached First Team, whose club is empty. It is included, because the inner join is not made. Make the inner 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.

This is the static Team.list path owned by #17071. The public-API control was verified there at 98e75e9ab182: fetch: [club: JoinType.INNER] excludes the team without a club. This part covers requested joins in where queries, detached criteria and dynamic finders; the static-list implementation stays in #17071.

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.

Third round, at f9362bd. The one new commit takes the three points of my second review:

  • The page: the note, the skill entry and "Results that change" now say that a paged query with a join type for a collection pages instances, so max: 2 can return two where 7.0.x returned one, and that 'join' and join('books') without a type still page the joined rows. That matches what I measured in round 2.
  • The projection: the right-join bullet says that a property projection returns a repeated value, null included, once, so its size can differ from the count.
  • The imports: WhereQueryWithAssociationSortSpec imports IgnoreIf and Requires once.

The code is the same as at 56639c2, so my round-2 probes stand. CI passed with the tests at this head. This part doesn't have the merge of #17066's new page assertion yet. It merges cleanly, and with it AssociationSortSpec, AssociationSortLeftJoinSpec and WhereQueryWithAssociationSortSpec pass (137 tests, 25 skipped).

On James's comment of today: it repeats his comment of 2026-11-19. Team.list(fetch: [club: JoinType.INNER]) is the static list, which #17071 changes, as you replied then. It returns 7 teams here, as on 7.0.x, and 5 at the stack top and at #17079. Since this part ships with #17071, nothing is missing here.

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

@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.

@testlens-app

testlens-app Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

⚠️ TestLens detected flakiness ⚠️

Test Summary

Tip

Inspect all details with the TestLens CLI: testlens pr 17067

CI / Redis Tests (25, 7.4) > :grails-test-examples-redis:integrationTest

Test Runs Flakiness
MemoizeObjectAnnotationSpec > testMemoizeAnnotationExpire ❌ ✅ 0% 🟢

🏷️ Commit: 4301e58
▶️ Tests: 11824 executed
⚪️ Checks: 58/58 completed

Test Failures

MemoizeObjectAnnotationSpec > testMemoizeAnnotationExpire (:grails-test-examples-redis:integrationTest in CI / Redis Tests (25, 7.4) | Attempt 1/2)
redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out
	at redis.clients.jedis.util.RedisInputStream.ensureFill(RedisInputStream.java:262)
	at redis.clients.jedis.util.RedisInputStream.readByte(RedisInputStream.java:55)
	at redis.clients.jedis.Protocol.process(Protocol.java:131)
	at redis.clients.jedis.Protocol.read(Protocol.java:221)
	at redis.clients.jedis.Connection.protocolRead(Connection.java:384)
	at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:397)
	at redis.clients.jedis.Connection.getOne(Connection.java:370)
	at redis.clients.jedis.Connection.executeCommand(Connection.java:175)
	at redis.clients.jedis.Jedis.flushDB(Jedis.java:395)
	at grails.plugins.redis.RedisService.flushDB_closure28(RedisService.groovy:437)
	at grails.plugins.redis.RedisService.withRedis(RedisService.groovy:104)
	at grails.plugins.redis.RedisService.flushDB(RedisService.groovy:436)
	at com.example.MemoizeObjectAnnotationSpec.setup(MemoizeObjectAnnotationSpec.groovy:36)
Caused by: java.net.SocketTimeoutException: Read timed out
	at java.base/sun.nio.ch.NioSocketImpl.timedRead(NioSocketImpl.java:277)
	at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:302)
	at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:354)
	at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:798)
	at java.base/java.net.Socket$SocketInputStream.implRead(Socket.java:974)
	at java.base/java.net.Socket$SocketInputStream.read(Socket.java:964)
	at java.base/java.io.InputStream.read(InputStream.java:222)
	at redis.clients.jedis.util.RedisInputStream.ensureFill(RedisInputStream.java:256)
	... 12 more

Learn more about TestLens at testlens.app/docs.

@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.

* query already has for the path is reused.
*/
private CriteriaAndAlias getOrRegisterJoinAt(String associationPath, String associationName) {
CriteriaAndAlias join = createdAssociationPaths.get(associationPath);

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 criteria names the players alias club, then joins club as an inner join. Unattached First Team, whose club is empty, is included. The alias is read as the join, so the inner join is not made. Make the inner join on the club association.

@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.

This branch has not been deployed

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

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

3 participants