Skip to content

Sort a criteria query by a property of an association - #17070

Merged
jdaugherty merged 10 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-10-criteria-order-association
Dec 2, 2026
Merged

jdaugherty merged 10 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-10-criteria-order-association

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Part 10 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.

order('club.name') in a criteria query failed with "could not resolve
property", and with a Query.Order it sorted by a property of the
queried class. A criteria query that is passed pagination arguments
and a sort by a path through more than one association failed when
totalCount was read, or with "duplicate association path" when the
criteria used the first association, and a map of sort properties
failed with a ClassCastException.

order now resolves an association path, also inside the criteria of an
association, and joins an association that the criteria do not join.
The orders are added once the criteria are
built, so an order uses the join and the join type that the criteria
or the fetch argument request, whichever comes first. An order by the
identifier of an association reads the foreign key, as before. The
sort argument reuses a join that the criteria have for a path, also
one made through an alias, and creates any other from the root
criteria, which is how the count recreates it.

The sort argument can also start with an alias that the criteria give
an association, as sort: 'c.name' with createAlias('club', 'c'), also
as an entry of a map of sort properties and followed by a further
association. Such a sort was dropped, which review 5868034911 of
#16853 reported for the map.

The join that an order makes is a left join only with the
grails.gorm.leftJoinAssociationSort setting. Without it the association
is joined with an inner join, as it is for the other sorts.

An order by an association uses the join that criteria on the
association make, with the left join type that a later join(String),
select(String) or fetch mode replaced there (#17192).

Results that change

  • What changes: order('author.name') in a criteria query works instead of failing. An order that is passed a Query.Order inside the criteria of an association sorts by the property of that association, not by the property of the queried class with the same name. A join made only for the order is an inner join, or a left join with grails.gorm.leftJoinAssociationSort.
  • Explicitly requested LEFT collection joins are preserved by criteria orders and sort arguments in both compatibility-setting modes, keeping roots whose collection is empty. Existing joined-row multiplicity is retained. Paged queries load these collections separately, so partial joined rows do not initialize incomplete collections.
  • A nested LEFT request also keeps intermediate joins made only for the criteria sort outer. Explicit intermediate join types, fetch modes that actually replace a requested join type, and joins used by association criteria retain precedence. A bare loading mode does not override the implied LEFT join. When the sort and requested path share their first association and then diverge, each remaining join follows its explicit type or the compatibility setting. Limited collection sorts still load complete collections separately.
  • How to get the old result: Move the order out of the criteria of the association.
  • Setting: No setting. A failing call now works, and the order of rows changes for a sort that was applied to another property; an alias-prefixed sort that continues through another association can exclude roots without it when the setting is off.

The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry.

A formerly ignored sort such as a.publisher.name now joins the publisher. With the compatibility setting off it can leave out roots without that association, and changes their paged totalCount. Remove the sort to retain the former unsorted rows, or enable leftJoinAssociationSort to retain them while sorting. The guide and skill now state this.

getJoinAlias exposes the existing canonical join lookup across the cfg/query package boundary so ordering reuses the join created by criteria. getWholeAssociationPath is protected because HibernateCriteriaBuilder, in another package, uses it when registering aliases. The same-release criteria-join changes depend on that path identity.

The Hibernate 7 criteria sort-map counterpart is tracked by #17166, related to the existing sort-map report #14653. It should land on 8.0.x before this part is released across both modules, and remains outside the requested-join scope of #17079.

Verification

At e431f96, after the merge of 7.0.x with #17192, AssociationJoinTypeSpec, AssociationSortSpec, NestedRequestedLeftJoinSpec, WhereQueryWithAssociationSortSpec and their LeftJoin subclasses pass (1,331 cases at the merge, zero failures), and codeStyle of the Hibernate 5 core module passes. At 14fca14 the full Hibernate 5 core suite passed (2,085 cases, zero failures, 65 skipped), as did root codeStyle, RAT, dependency-version validation and the guide build.

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.

order('club.name') in a criteria query failed with "could not resolve
property", and with a Query.Order it sorted by a property of the
queried class. A criteria query that is passed pagination arguments
and a sort by a path through more than one association failed when
totalCount was read, or with "duplicate association path" when the
criteria used the first association, and a map of sort properties
failed with a ClassCastException.

order now resolves an association path, also inside the criteria of an
association, and joins with a left join an association that the
criteria do not join. The orders are added once the criteria are
built, so an order uses the join and the join type that the criteria
or the fetch argument request, whichever comes first. An order by the
identifier of an association reads the foreign key, as before. The
sort argument reuses a join that the criteria have for a path, also
one made through an alias, and creates any other from the root
criteria, which is how the count recreates it.

The sort argument can also start with an alias that the criteria give
an association, as sort: 'c.name' with createAlias('club', 'c'), also
as an entry of a map of sort properties and followed by a further
association. Such a sort was dropped, which review 5868034911 of
apache#16853 reported for the map.

The join that an order makes is a left join only with the
grails.gorm.leftJoinAssociationSort setting. Without it the association
is joined with an inner join, as it is for the other sorts.

Part 10 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. A sort through an alias stops at the first property and does not join the rest.

@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 e54321e (base 7.0.x): 4a6224d, f2e1cc6 and the merge of #17069's head. The merge drops #17069's addOrderPossiblyNested, which this part replaces. The criteria probes of my review of #17069 return the same here as at #17069, with the setting off and on, so its sort fixes are kept.

I probed order and the sort argument of criteria queries, by a property of an association, a nested path, an alias, a hasOne, inside the criteria of an association, with a requested join type, paged, as a map, and with count, get and projections:

The failing calls work. With the setting off, they return the rows and the order of Hibernate 7 at #17079, apart from a map of sort properties (point 2) and a totalCount of a sort (below the table):

7.0.x and #17069 This head #17079
Team.createCriteria().list { like('name', '%First%'); order('club.name') }, also desc, withCriteria, a projection of name and order('club.name') inside a club { } block could not resolve property 4 teams, by club 4
Player.createCriteria().list { order('team.club.name') }, also order('contract.salary') of a hasOne could not resolve property 6 players 6
Player.createCriteria().list { team { like('name', '%First%'); order('club.name') } }, also order('team.club.name') after the block throws 3 3
Player.createCriteria().list(max: 2, sort: 'team.club.name') { … } could not resolve property: club 2, totalCount 6 2, totalCount 7
the same with team { like('name', '%First%') } throws, duplicate association path: team on 7.0.x 2, totalCount 3 2, totalCount 4
order('club.name') with join('club', JoinType.LEFT) or fetch: [club: JoinType.LEFT] could not resolve property 5, the team without a club first 5
list(sort: ['club.name': 'desc', name: 'asc']) { … }, also ['c.name': 'desc'] with createAlias('club', 'c') ClassCastException 4 ClassCastException

order('club.id') reads the foreign key, as before. club { order(Query.Order.desc('name')) } now sorts by the name of the club, as at #17079, where 7.0.x sorted by the name of the team. A totalCount that differs from Hibernate 7 is the count of #16863, which leaves out the join of the sort.

Needs a fix

1. Rows change with the setting off. The description says "no rows change by default". A sort that starts with an alias and goes on to another association was ignored, and now joins that association with an inner join, as a sort does without the setting:

Player.createCriteria().list(sort: 't.club.name') { createAlias('team', 't'); like('name', '%') } 7.0.x This head, setting off Setting on Hibernate 7 on 8.0.x and #17079
players 7, unsorted 6, by club 7, by club 6
totalCount 7 6 7 7

Hibernate 7 leaves the player out as well, so this needs no setting. But "Results that change", the note and the skill entry should say that such a sort also leaves out the instances without the association, unless grails.gorm.leftJoinAssociationSort is enabled. The note's advice, "Remove the sort to get the results unsorted, as before", keeps the rows as well, and could say so.

sort: 'c.name' with createAlias('club', 'c') keeps its rows, since the alias already joins the club with an inner join.

2. No Hibernate 7 counterpart. #17079 is the counterpart of #17067, #17068, #17069 and #17071. A map of sort properties in a criteria query still throws a ClassCastException with Hibernate 7, on 8.0.x and at #17079. After the merge-up, that call works with Hibernate 5 and fails with Hibernate 7. Hibernate 7 needs the same fix, in #17079 or in a pull request of its own, merged before this one, as for the other parts.

3. New API on 7.0.x, as on #17067 and #17069: the public static GrailsHibernateUtil.getJoinAlias, and the protected AbstractHibernateCriteriaBuilder.getWholeAssociationPath, which every subclass of HibernateCriteriaBuilder inherits. getJoinAlias has one caller, in AbstractHibernateCriteriaBuilder. getWholeAssociationPath is protected because HibernateCriteriaBuilder calls it. The description should say why each is needed on a patch branch.

4. Add run ci, and resolve the conflicts with 7.0.x, as on the other parts. Locally, the tests of grails-data-hibernate5-core pass at this head (1285 tests, 60 skipped). The stack top returns the same rows as this head for all of these queries.

Notes

  1. On James's comment, list(sort: 't.club.name') { createAlias('team', 't') } works at this head, with the rows of point 1.

  2. Team.createCriteria().count { like('name', '%First%'); order('club.name') } still fails, now with Column "CLUB_ALIAS1_.NAME" must be in the GROUP BY list instead of could not resolve property. Hibernate 7 returns 5. An order in a criteria count fails on 7.0.x for any property, as I noted on #17064, so that isn't this part's to fix.

  3. order('players.name') returns the team with three players three times, as Hibernate 7 on 8.0.x does. #17079 returns each team once, as it does for the other collection joins of a criteria query (point 2 on #17069).

  4. The description names 4a6224d as the change to review. f2e1cc6 is on top of it.

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

Name the inner join added by a formerly ignored alias-prefixed sort and how to retain the old rows. Merge the reviewed criteria-join fixes and keep the existing join lookup private.

@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 left join the call asked for still drops a team with no players when the sort is by a player property.

@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 6ff6caf. Points 1, 3 and 4 of my first review are fixed, and point 2 is below:

  1. "Results that change", the note and the skill entry say that a sort through an alias that goes on to another association, as in sort: 't.club.name' with createAlias('team', 't'), leaves out the instances without that association unless the setting is enabled. They also say how to keep the rows. With join('team.club', JoinType.LEFT), the 7 players stay, as with Hibernate 7.
  2. The description says why getJoinAlias and getWholeAssociationPath are needed. I'm fine with that.
  3. The pull request merges cleanly with 7.0.x and has run ci, and CI passed with the tests.

My probes from the first review give the same results here as at e54321e, with the setting off and on, and the criteria probes of #17069 give what they give at #17069 (5ed82d5). The tests of grails-data-hibernate5-core pass here (1344 tests, 65 skipped), and the guide builds.

Needs a fix

1. James's new comment holds: a sort or an order by a collection doesn't use a left join that the criteria query requests for the collection.

Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { } 7.0.x, #17069 and this head the where query with the same arguments, here #17079
teams Playerless First Team and Empty Team left out; Squad Team three times all 7 all 7

The same goes for the call without max, for join('players', JoinType.LEFT) instead of the fetch argument, and for order('players.name'), which threw on 7.0.x and works here. The setting changes none of them.

For an association to a single instance it works: list(max: 10, sort: 'club.name', fetch: [club: JoinType.LEFT]) keeps the teams without a club, as at #17079. The description says that "an order uses the join and the join type that the criteria or the fetch argument request", and the note says that a left join that the query requests keeps the rows. For a collection, neither holds. The where query of the same stack keeps the teams, and #17079 does too, so after the merge-up the criteria query of Hibernate 5 and of Hibernate 7 return different rows.

Making the requested left join of a collection before the sort and the orders, so that they use it, as 429b6d5 does for an association to a single instance, would keep the teams. As for the other collections that a criteria query fetches (#17069), a team would then come once for each of its players.

2. Nothing tracks the Hibernate 7 counterpart. The description says that the fix for a map of sort properties with Hibernate 7 is a follow-up that should land before this part is released, but there's no issue or pull request for it. A map of sort properties in a criteria query still throws a ClassCastException with Hibernate 7, on 8.0.x and at #17079 (1cba001). An issue, named in the description next to the release ordering, would keep it from being missed when the stack is merged up.

Smaller points

  • The description still names 4a6224d as the change to review. f2e1cc6 and 6ff6caf are part of it too.
  • The imports of WhereQueryWithAssociationSortSpec are reordered again here.

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. A left join the call asked for is still undone by a sort on the static list.

} else if (property instanceof Association) {
final Association<? extends Property> a = (Association<? extends Property>) property;
final Join join = queryRoot.join(sortHead);
final Join join = getOrCreateSortJoin(queryRoot, sortHead, !(a instanceof ToMany) && GrailsHibernateUtil.isLeftJoinAssociationSort(entity));

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(sort: 'players.name', fetch: [players: JoinType.LEFT]) should include Playerless First Team. It is left out. The left join is not made, and the sort joins players as an inner join. 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.

This static-list collection-fetch case belongs to #17071. The public Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]) control was verified there at 98e75e9ab182 and keeps the team with no players. #17070 covers criteria orders and criteria sort arguments; the static-list implementation stays in #17071.

@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 left join the call asked for is still undone by a sort on the static list.

} else if (property instanceof Association) {
final Association<? extends Property> a = (Association<? extends Property>) property;
final Join join = queryRoot.join(sortHead);
final Join join = getOrCreateSortJoin(queryRoot, sortHead, !(a instanceof ToMany) && GrailsHibernateUtil.isLeftJoinAssociationSort(entity));

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(sort: 'players.name', fetch: [players: JoinType.LEFT]) should include Playerless First Team. It is left out. The left join is not made, and the sort joins players as an inner join. 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.

Team.list(...) is the static list, which #17071 changes. It goes through HibernateGormStaticApi and GrailsHibernateQueryUtils, and this pull request changes neither: its changes are in the criteria builder (HibernateCriteriaBuilder, AbstractHibernateCriteriaBuilder) and in the sort that the criteria builder applies in GrailsHibernateUtil. With the teams of AssociationJoinTypeSpec, with and without grails.gorm.leftJoinAssociationSort, Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]), also with max: 10, returns the four teams that have players on 7.0.x (ffd848b) and at this head (e431f96). At #17071's head (89f16e8) it returns all five teams, each once, Playerless First Team included. The criteria query of this pull request, Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { }, returns all five here.

@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 9dc26a4. Since my second review, 28e5534 fixed both of its points, and 9dc26a4 merged #17069's head. That merge brings #17067's new rule: a sort through a path below a requested JoinType.LEFT keeps the associations of the path outer. It also applies the rule to criteria queries. Apart from the criteria part, the tree is that of my own merge of 28e5534 and 1e09b41.

The points of my second review are fixed:

  1. A sort or an order by a collection keeps the left join that the criteria query requests. Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { } now keeps Playerless First Team and Empty Team, with the setting off and on. So do the call without max, join('players', JoinType.LEFT) instead of the fetch argument, and order('players.name'). Squad Team comes once for each of its 3 players, and totalCount counts those rows. Hibernate 7 returns each team once. A criteria query sorted by a collection repeats its roots on 7.0.x too, as sort: 'players.name' without a join type shows, and the note says that the rows per element stay. So I'm fine with that. On a paged query, the collection is loaded when accessed, with all its elements.
  2. #17166 tracks the Hibernate 7 counterpart for a map of sort properties, and the description names it next to the release ordering.

The smaller points are settled too. The description says to review the changes relative to #17069, and the merge keeps one import of each class in WhereQueryWithAssociationSortSpec.

The new rule in criteria queries

I ran it with the domain of my earlier probes at this head and at 28e5534, on 7.0.x (28f27fe), and with Hibernate 7 on 8.0.x (99aedeb) and at #17079 (053255f):

7.0.x This head, setting off and on Hibernate 7
Team.createCriteria().list(sort: 'players.contract.salary') { join('players.contract', JoinType.LEFT) }, also with order, with fetch instead of join, with max: 10 and with a sort map throws all 7, Squad Team 3 times all 7, each once; the sort map throws (#17166)
order('players.name') or order(Query.Order.asc('players.name')) with join('players.contract', JoinType.LEFT) throws, or 5 teams with Query.Order all 7 all 7
A player without a team, in Player.createCriteria().list(sort: 'team.name') { join('team.club', JoinType.LEFT) } left out kept kept

At 28e5534 the first row returned the 5 teams with players, Squad Team 3 times. order('team.name'), order('team.club.name') and join('team.players', JoinType.LEFT) with order('team.players.name') keep that player too, as at 28e5534. createAlias('players', 'p') before join('players.contract', JoinType.LEFT) keeps its inner join, and fetch: [players: 'select', 'players.contract': JoinType.LEFT] keeps all 7 teams, both as with Hibernate 7. 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.

The sort argument by a property of the collection itself

Team.createCriteria().list(sort: 'players.name') { join('players.contract', JoinType.LEFT) } still leaves out the two teams without players, with the setting off and on. So do fetch: ['players.contract': JoinType.LEFT] instead of the join, a sort map and max: 10. In the same query, order('players.name') and order(Query.Order.asc('players.name')) keep them. So do the where query Team.where { name ==~ '%' }.list(fetch: ['players.contract': JoinType.LEFT], sort: 'players.name') at #17067, and Hibernate 7 on 8.0.x and at #17079. On 7.0.x the sort argument also returns the 5 teams, so this isn't a regression. But the note says that the rule applies to the criteria sort, and order and sort now differ in the same query.

applyRequestedSortJoins makes the left join for the sort argument only when the sort is below a requested path, wholePath.startsWith(requested.getKey() + '.'). With sort: 'players.name' and a request for players.contract, the requested path is below the association of the sort instead, so the argument utilities join players with their inner join. I think that calling calculateOrderPropertyName in that case too, when requested.getKey() starts with the association path of the sort and a dot, fixes it, as isRequestedLeftSortJoin then picks the left join. A row with sort: 'players.name' for the path players.contract in a criteria #ordering keeps the left join of #path would cover it.

What I ran

  • My probes of the first two rounds and of the count below: apart from the rows above, they give the same results as at 28e5534, with the setting off and on.
  • The grails-data-hibernate5-core tests: they pass at this head (1555 tests, 60 skipped), and the guide builds. This head has #17066's new page assertion, through #17067.

CI passed with the tests.

On James's comment of yesterday: Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]) is the static list, which #17071 changes, as jdaugherty replied. Here it returns what 7.0.x returns, without the two teams that have no players. At #17071 it returns all 7 teams, each once, as at #17079.

Optional

  • A milestone for #17166. The description says #17166 should land on 8.0.x before this part is released. Putting it on grails:8.0.1 would keep it from being missed.

FYI, not for this part

The totalCount of a paged where query sorted by a collection counts the joined rows, not the instances that list returns:

Team.where { name ==~ '%' }.list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) list totalCount
7.0.x 5 7
#17062 to this head, with the setting off and on 7 9
Hibernate 7, on 8.0.x and at #17079 7 7

Without a join type it's 5 and 7 on every head of the stack, as on 7.0.x. #17067's new rule gives the same count: fetch: ['players.contract': JoinType.LEFT], sort: 'players.contract.salary' lists 7 teams and counts 9. It comes from 7.0.x and isn't made here, so it's for an issue of its own, which I can open.

@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 f5b627c. Since my third review, f5b627c makes the sort argument use the requested left join also when the requested path is below the association of the sort, as I suggested. It adds rows for players.name and p.name to AssociationJoinTypeSpec and names the sort by books.title in the note and the skill. The description still says to review the changes relative to #17069, and the branch merges cleanly with 7.0.x at 0c81611.

The point of my third review is fixed, with the setting off and on:

7.0.x (0c81611) 9dc26a4 This head Hibernate 7 at #17079 (eed6c6e)
Team.createCriteria().list(sort: 'players.name') { join('players.contract', JoinType.LEFT) }, also with fetch: ['players.contract': JoinType.LEFT], with a sort map, with max: 10 and with order: 'desc' the 5 teams with players, Squad Team 3 times; the sort map throws the 5 teams, Squad Team 3 times all 7, Squad Team 3 times all 7, each once; the sort map throws (#17166)

A page holds the teams without players too: list(max: 3, sort: ['players.name': 'asc', name: 'asc']) with the same join returns Arsenal First Team and the two teams without players. Squad Team alone on a page of 1 has its 3 players when they're accessed. join('players', JoinType.INNER), createAlias('players', 'p') (also with sort: 'p.name'), JoinType.INNER for players.contract, and a criterion on players keep their inner join, as with Hibernate 7. A sort by club.name, or through team.club for a player, gives the same as at 9dc26a4.

Needs a fix

  1. A fetch mode for the collection makes the join of the sort inner. With the setting off and on:

    7.0.x This head Where query at this head Hibernate 7 at #17079
    Team.createCriteria().list(fetch: [players: 'select', 'players.contract': JoinType.LEFT], sort: 'players.name') { }, also with 'join', 'lazy' or 'eager' for players, with max: 10, with order('players.name'), and with select('players'), join('players') or fetchMode('players', FetchMode.SELECT) next to join('players.contract', JoinType.LEFT) the 5 teams with players, Squad Team 3 times; order throws the 5 teams, Squad Team 3 times all 7 all 7
    The same sorted by players.contract.salary, with 'select' or 'join', order or select('players') throws the 5 teams, Squad Team 3 times all 7 all 7
    The same without a sort, or with sort: 'name' all 7 all 7 all 7 all 7

    The where query column is Team.where { name ==~ '%' }.list(...) with the same fetch and sort, also as a detached criteria with join('players') or select('players'), and as findAllByNameLike. For an association to a single instance, as in Player.createCriteria().list(fetch: [team: 'select', 'team.club': JoinType.LEFT], sort: 'team.name') { }, the criteria query keeps the player without a team, as the where query does.

    Every fetch mode adds its path to explicitFetchModes, and isRequestedLeftSortJoin returns false for a path there, so calculateOrderPropertyName joins players with an inner join, whatever the setting. The specs only try a fetch mode that replaces a JoinType.INNER for the same path: join('players', JoinType.INNER) followed by a fetch mode here, and join('children', JoinType.INNER).select('children') in #17067's NestedRequestedLeftJoinSpec. The where query keeps the inner join in that case, and only then. A fetch mode says how to load the collection, not how to join it for the sort, so I think the criteria query should do as the where query does: add the path to explicitFetchModes only when the fetch mode replaces a requested join type. In join(String), select, fetchMode and the fetch argument:

    if (requestedJoinTypes.remove(getRequestedJoinPath(associationPath)) != null) {
        explicitFetchModes.add(getRequestedJoinPath(associationPath));
    }

    With that, the criteria queries above keep the two teams without players, and a fetch mode after join('players', JoinType.INNER) keeps the inner join, in both APIs. "Replacement fetch mode" in the note then means the same as in #17067's note. A feature with the fetch mode alone, next to a nested LEFT criteria #sortForm by #sortProperty respects the intermediate #request request, would cover it.

  2. A sort through another association of the collection ignores the setting. Team.createCriteria().list(sort: 'players.team.name') { join('players.contract', JoinType.LEFT) } returns the 5 teams with players, Squad Team 3 times, with the setting off and on. The where query Team.where { name ==~ '%' }.list(fetch: ['players.contract': JoinType.LEFT], sort: 'players.team.name') and Hibernate 7 at #17079 return the 5 teams with the setting off, and all 7 with it on. On 7.0.x the criteria query throws.

    applyRequestedSortJoins makes the joins of the sort only when the request is below the association of the sort or the sort is below the request, so for players.contract and players.team the argument utilities join players with their inner join. Matching every left request that starts with the first association of the sort fixes it, since isRequestedLeftSortJoin still decides each association of the path: players stays outer because of the request below it, and team follows the setting:

    int firstPropertyPos = wholePath.indexOf('.');
    if (firstPropertyPos < 0) {
        continue;
    }
    String firstAssociation = wholePath.substring(0, firstPropertyPos + 1);
    for (Map.Entry<String, JoinType> requested : requestedJoinTypes.entrySet()) {
        if (requested.getValue() == JoinType.LEFT && (requested.getKey() + '.').startsWith(firstAssociation)) {

    With that, the query returns all 7 teams with the setting on and the 5 teams with it off, as the where query does. A row that sorts by players.team.name with the setting enabled would cover it.

With both changes, no other row of my probes changes, and the grails-data-hibernate5-core tests pass (1680 tests, 65 skipped).

What I ran

  • My probes of the earlier rounds: apart from the rows above, they give the same results as at 9dc26a4, with the setting off and on. A page that ends among equal sort values, such as nulls, can hold other teams from one run to the next.
  • New rows for the cases above: at this head and at 9dc26a4, on 7.0.x at 0c81611, and with Hibernate 7 on 8.0.x (99aedeb) and at #17079 (eed6c6e).
  • The grails-data-hibernate5-core tests: they pass at this head (1680 tests, 65 skipped), and the guide builds.

CI passed with the tests.

A correction to my third review

My third review said that fetch: [players: 'select', 'players.contract': JoinType.LEFT] with a sort by players.contract.salary keeps all 7 teams. That was wrong. At 9dc26a4 it returned 7 rows, Squad Team 3 times, without the two teams that have no players, as in point 1.

Smaller points

  • The description's "Verification" is for 9dc26a4.
  • James's inline comment of 11-25 is about the static list again, which #17071 changes. At #17071's head, 5767310, Team.list(fetch: [players: JoinType.LEFT], sort: 'players.name') returns all 7 teams, each once.

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. A left join the call asked for is still undone by a sort on the static list.

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(sort: 'players.name', fetch: [players: JoinType.LEFT]) should include Playerless First Team. It is left out. The left join is not made, and the sort joins players as an inner join. 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.

This is the static Team.list path owned by #17071. Its public LEFT collection-fetch/sort control keeps the team without players. #17070 handles criteria orders and criteria sort arguments; the static-list change remains in #17071.

A criteria query keeps a join type that a fetch mode replaced for the
join that its criteria on the association make, and an order or the
sort argument by a property of the association uses that join. The new
feature orders after and inside an association block, with a
Query.Order, through an alias and with the sort argument, after
join('club', JoinType.LEFT) followed by join('club') or select('club'),
and keeps the teams without a club in both setting modes. Without the
replaced join type every row leaves those teams out, and without the
criteria orders by an association path the orders after the block fail.
@github-actions
github-actions Bot dismissed matrei’s stale review November 27, 2026 20:59

Dismissed automatically: the pull request changed after this approval, from 14fca14 to e431f96.

@testlens-app

testlens-app Bot commented Nov 27, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: e431f96
▶️ Tests: 61889 executed
⚪️ Checks: 58/58 completed


Learn more about TestLens at testlens.app/docs.

@jdaugherty jdaugherty left a comment

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.

@jamesfredley, review 6077551227 and the earlier reviews with the same text: On the static list: Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]) is changed by #17071, not here. This pull request changes the criteria builder only. The static call returns the same four teams here as on 7.0.x, and all five, each once, at #17071's head (89f16e8), with and without grails.gorm.leftJoinAssociationSort. The criteria form, Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { }, keeps Playerless First Team here (fixed in 28e5534). The branch now also merges 7.0.x with #17192: an order by an association uses the join that the criteria make for it, with a left join type that a later join('club') or select('club') replaced. The new feature in AssociationJoinTypeSpec, 'an order of a criteria query uses the join that criteria on the association make with the join type that a fetch mode replaced', covers it (e431f96).

@matrei: Merged 7.0.x with #17192 in 54c8972. #17192's supersededJoinTypes holds the paths that explicitFetchModes held, filled and emptied by the same calls, so the sort now reads supersededJoinTypes and explicitFetchModes is gone. The replaced join types are cleared after the orders, as the requested ones are. e431f96 adds a feature for orders (after and inside the block, Query.Order, alias, sort argument) that use the join whose replaced left join type the criteria keep. All of its rows fail without #17192, and the orders after the block fail without this part. The case you noted for #17191, where the sort's own join after a replaced JoinType.LEFT is inner, is unchanged.

Related, by @borinquenkid: #17052 also fixes a map as the sort argument of a paged criteria query and the second join of a sort through an association that the criteria joined, in the same paginationEnabledList branch of AbstractHibernateCriteriaBuilder. #17014 removes the call that makes the join of a sort take the cache setting of the associated class's mapping, a call that this part moves into its rewritten GrailsHibernateUtil.addOrderPossiblyNested. A note on each says how the two meet.

} else if (property instanceof Association) {
final Association<? extends Property> a = (Association<? extends Property>) property;
final Join join = queryRoot.join(sortHead);
final Join join = getOrCreateSortJoin(queryRoot, sortHead, !(a instanceof ToMany) && GrailsHibernateUtil.isLeftJoinAssociationSort(entity));

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(...) is the static list, which #17071 changes. It goes through HibernateGormStaticApi and GrailsHibernateQueryUtils, and this pull request changes neither: its changes are in the criteria builder (HibernateCriteriaBuilder, AbstractHibernateCriteriaBuilder) and in the sort that the criteria builder applies in GrailsHibernateUtil. With the teams of AssociationJoinTypeSpec, with and without grails.gorm.leftJoinAssociationSort, Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]), also with max: 10, returns the four teams that have players on 7.0.x (ffd848b) and at this head (e431f96). At #17071's head (89f16e8) it returns all five teams, each once, Playerless First Team included. The criteria query of this pull request, Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { }, returns all five here.

}
associationPath = associationPath == null ? sortHead : associationPath + '.' + sortHead;
criteria = getOrCreateSortCriteria(c, criteria, associationPath, sortHead,
persistentProperty instanceof ToMany || !isLeftJoinAssociationSort(persistentProperty.getOwner()));

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(...) is the static list, which #17071 changes. It goes through HibernateGormStaticApi and GrailsHibernateQueryUtils, and this pull request changes neither: its changes are in the criteria builder (HibernateCriteriaBuilder, AbstractHibernateCriteriaBuilder) and in the sort that the criteria builder applies in GrailsHibernateUtil. With the teams of AssociationJoinTypeSpec, with and without grails.gorm.leftJoinAssociationSort, Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]), also with max: 10, returns the four teams that have players on 7.0.x (ffd848b) and at this head (e431f96). At #17071's head (89f16e8) it returns all five teams, each once, Playerless First Team included. The criteria query of this pull request, Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { }, returns all five here.

jdaugherty added a commit to jdaugherty/grails-core that referenced this pull request Nov 28, 2026
…r its association

createAlias without a join type requested an inner join for its path, which
replaced a join type that the query requested for the association before
the alias, and one that a later fetch mode had replaced, so
join('club', JoinType.LEFT); createAlias('club', 'c') left out the teams
without a club. Hibernate 5 joins such an alias with the requested type, as
the merged apache#17192 and the open apache#17070 specify. The alias now takes that type
and leaves the request and the fetch mode as they are. A join type that an
earlier alias of the same path configured is that alias's own, so a second
alias of the path still has an inner join of its own.

AssociationJoinTypeSpec gets the rows of the Hibernate 5 spec for an alias:
the alias form of a requested left join before, after and in the fetch
argument, the criteria-query feature of apache#17192 with an alias and an alias
made through another alias, and the order feature of apache#17070, also through
an alias.

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

Sixth round, at e431f96. It merges 7.0.x at ffd848b, which has #17192, and adds a feature for the orders that use the join whose replaced join type the criteria keep. The merge resolves the conflict in AbstractHibernateCriteriaBuilder. #17192's supersededJoinTypes gets and loses the same paths as this part's explicitFetchModes did, so the sort reads it now, and both maps are cleared once the orders are added. The grails-data-hibernate5-core tests pass (2120 tests, 60 skipped), the guide builds, the branch merges cleanly with 7.0.x at ffd848b, and CI passed. The description no longer says that this part is stacked on #17069, which was the smaller point of my fifth review.

The merge

My probes of the earlier rounds give the same results as at 14fca14, with the setting off and on. The only differences are pages that start among rows with equal sort values. These probes include the rows of my fourth review:

  • a fetch mode alone,
  • the sort of a sibling path,
  • a fetch mode after JoinType.INNER.

The case that I noted for #17191 is unchanged, as jdaugherty says. That's the case where the sort makes its own join after a fetch mode replaced JoinType.LEFT. Team.createCriteria().list(sort: 'club.name') { join('club', JoinType.LEFT); select('club') } still returns the 5 teams with a club with the setting off. 7.0.x at ffd848b does the same, and the detached criteria and the where query return all 7. That stays with #17191.

A fetched collection that holds the elements of another

While reviewing #17072, I found that a page can fill a fetched collection with the elements of another collection of the same class. On a page, the left join that a sort makes of a collection gets the WITH clause 1=1, so that Hibernate doesn't fetch the collection from the rows of the page. Hibernate then fills another fetched collection of the same class from the columns of that join. In the criteria query, this part does that in createAlias for the join of the sort. With squads where S1 has the players p1 and p2 and the reserves r1 and r2, S2 has the player p3, and S3 has neither:

7.0.x (ffd848b) This head #17072 (02b0749)
Squad.createCriteria().list(max: 1, offset: 1, sort: 'players.name') { join('players', JoinType.LEFT); join('reserves') } S1 with one of its reserves S1, whose reserves holds the player p1 S1 with both reserves
The same with order('players.name') in the closure in place of the sort argument throws could not resolve property: players.name the same as above the same as above
Squad.createCriteria().list(max: 2, sort: 'players.name', fetch: [players: JoinType.LEFT, reserves: 'join']) { } S1 twice, with both reserves S3, and S1, whose reserves holds p1 S3, and S1 with both reserves
Squad.createCriteria().list(max: 1, offset: 1, sort: 'players.name', fetch: ['players.contract': JoinType.LEFT, reserves: 'join']) { }, also with join('players.contract', JoinType.LEFT) in the closure S1 with one of its reserves S1, whose reserves holds p1 S1 with both reserves
The same with sort: 'players.contract.salary' throws could not resolve property: contract the same as above the same as above
Squad.where { name ==~ '%' }.list(max: 1, offset: 1, sort: 'players.name', fetch: ['players.contract': JoinType.LEFT, reserves: 'join']), also with sort: 'players.contract.salary', with max: 2, and with findAllByNameLike S1, whose reserves holds p1 the same S1 with both reserves

It happens with the setting off and on. Without a page, these queries load both reserves.

As the last row shows, 7.0.x has this already. It came with #17067: at the merge of #17066 (4031b94) the where query loads one of the two reserves, and at the merge of #17067 (70ca112) it loads p1. On 7.0.17 (9706903), the where query sorted by players.name loads one of the two reserves, and the sort by players.contract.salary throws. This part extends it to the criteria query. That covers a nested left join and the collection that the left join is requested for, which 7.0.x gets right. For the first three rows, #17071 at 3128803 and at 89f16e8 gives the same results as this head, and so does this part at 14fca14, which I approved.

#17072 loads the other collection after the query, which fixes every row. I don't think this needs to hold up this part, since 7.0.x has the bug already and #17072 fixes it. But 7.0.18 shouldn't be staged before #17072 is merged.

What I ran

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. A sort by a collection name that is also an alias still leaves out a team with no players.

@jdaugherty
jdaugherty merged commit e2737c1 into apache:7.0.x Dec 2, 2026
59 checks passed
@jdaugherty
jdaugherty deleted the fix/16853-10-criteria-order-association branch December 2, 2026 18:36
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Pull request #17071 was merged into this branch, the copy of the head of
#17070 that it was stacked on, and not into 7.0.x. This merge brings it in.
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Carries #17070 (order in a criteria query sorts by a property of an
association) and #17071 (list and the example finders apply a join type in
their fetch argument).

- upgrading60x.adoc keeps the 7.1.x side; the changes to the 7.0.18 notes
  are applied to upgrading70x.adoc, where 7.1.x keeps them.
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Carries #17070 and #17071 from 7.0.x. No conflicts.
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Carries #17070 (order in a criteria query sorts by a property of an
association) and #17071 (list and the example finders apply a join type in
their fetch argument) for Hibernate 5.

- GrailsHibernateQueryUtils.populateArgumentsForCriteria keeps both sides:
  8.0.x's validation of the sort property and of the direction, and 7.x's
  join types of the fetch argument, which a sort by the association uses.
- HibernateGormStaticApi keeps the imports of both sides.
- FetchJoinTypeSpec imports the entities from grails.gorm.tests.entities and
  registers them with the manager, as the other specs do on 8.0.x.
- The changes to the 7.0.18 notes are also in the 8.0.1 section of
  upgrading80x.adoc, and in the 8.0.1 part of the upgrade skill, under
  "GORM for Hibernate 5".
- Two features of the Hibernate 5 example application were pending on these
  fixes and pass now, so they lose @PendingFeature: a fetch join in list
  that keeps the club without a team (QueryEntryPointScenariosSpec) and an
  order by an alias-qualified path (AliasRulesScenariosSpec).
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Carries #17070 and #17071 (Hibernate 5, from 7.0.x) and #16863 (a sort by an
association with Hibernate 7).

- JpaCriteriaQueryCreator.assignOrderBy is the 8.0.x method with 8.1.x's
  order handlers: the handler of a Query.Order subclass still builds its
  order, a count still leaves such an order out, and a distinct list that a
  handler orders by something other than a column of the entity is made
  distinct in memory, as for the other orders.
- JpaQueryContext keeps 8.0.x's getSortExpression and isColumnOfRoot, and
  8.1.x's @OverRide on getFullyQualifiedPath.
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Carries #17070 and #17071 (Hibernate 5, from 7.0.x) and #16863 (a sort by an
association with Hibernate 7). Resolved as #17074 asks for the merge of the
7.0.x sort changes: the 7.0.x code plus the rejection of a sort by an alias
that the query does not define.

- GrailsHibernateUtil.addOrderPossiblyNested is the 7.0.x method, which
  resolves an alias that the criteria give an association, and throws
  "Invalid sort property" for a name that is neither a property of the
  queried class nor an alias of the criteria. 9.0.x's isAlias is no longer
  used and is removed.
- JpaCriteriaQueryCreator.assignOrderBy is the 8.1.x method; an order that
  resolves to nothing is rejected in a count as well, as #17074 made it.
- The Hibernate 7 HibernateGormStaticApi keeps both sides: findWhere and
  findAllWhere validate the sort before they return for an empty example,
  and run a sorted call as a criteria query.
- The upgrade skill keeps 9.0.x's side, the Grails 9 skill, which has no
  8.0.1 part.
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Carries #17070 and #17071 (Hibernate 5) and #16863 (Hibernate 7), with the resolutions of the 9.0.x merge. No conflicts.
jdaugherty added a commit that referenced this pull request Dec 2, 2026
Carries #17070 and #17071 (Hibernate 5) and #16863 (Hibernate 7), with the resolutions of the 9.0.x merge. No conflicts.
jdaugherty added a commit to jdaugherty/grails-core that referenced this pull request Dec 2, 2026
…into collection sorting

7.0.x now has apache#17070 and apache#17071, the two parts below this one, and the other changes merged since. No conflicts.
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.

3 participants