Skip to content

Sort by a path that starts with the alias of the queried class - #17073

Open
jdaugherty wants to merge 62 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-13-sort-root-alias
Open

jdaugherty wants to merge 62 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-13-sort-root-alias

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Part 13 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 #17072. 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 #17072.

A sort that starts with the alias that a detached criteria gives the
queried class, as in
new DetachedCriteria(Team, 't').list(sort: 't.name'), was ignored: the
query returned its rows unsorted, without an error. Such a sort now
sorts by the rest of its path, in where queries, detached criteria,
list, the example queries and the sort argument of a criteria query.

Results that change

  • Root-alias-prefixed sorts now apply their remaining path. For association paths, the new inner join can exclude roots without the association from list, count and totalCount when the compatibility setting is off. Enable leftJoinAssociationSort or request LEFT to retain them while sorting; remove the sort for the former unsorted rows.
  • An invalid remaining property now fails as the same unqualified invalid property does. Undefined aliases remain outside this change and are addressed on 9.0.x by Reject a sort by an alias that the query does not define #17074.
  • A valid association path keeps its old meaning when its first segment is also the root alias. The root alias is stripped once only when the full association path does not resolve, preserving the doubled-alias fix without changing a working association sort. Nested joins are qualified through their parent alias, including paths through collections and multiple associations.

The Hibernate 7 root-alias sort and detached-criteria restriction counterpart is tracked by #17167, including the finding on #17063. It must be coordinated on 8.0.x before release across both modules, separately from requested-join handling in #17079. The Grails 9 merge-up must preserve declared root aliases alongside the undefined-alias rejection in #17074.

Verification

At 060fe90, including the reviewed #17072 parent, the full Hibernate 5 core suite has 2,227 cases: 2,059 passed, 168 skipped and zero failures. Regressions retain players.team.name and team.club.name coverage and add 24 variants of the exact players.team LEFT-fetch case, with a colliding root alias and a no-alias control, argument/stored/map sorts, paging on/off and both compatibility settings. All 24 pass; the 12 setting-off variants failed before the corrected lower parent was included. This verifies the inherited requested-join fix, not a separate alias-runtime change. Root codeStyle, RAT (zero unknown licenses), dependency-version validation and the guide build passed. The whole reviewed 7.0.x stack is included.

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 17 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.
Team.where { ... }.join('club', JoinType.INNER) lists and counts the
teams with a club, but deleteAll and updateAll on it ignored the join
type and deleted or updated the teams without a club as well. They now
modify the instances that list returns.

An update or a delete cannot join, so each requested join becomes a
restriction: a subquery that selects from the entity of the first
association on the path and joins the rest of it. deleteAll selects the
identifiers first when the path starts with a collection that has a
join table, because Hibernate deletes the join rows before the
instances with the same restriction. A one-to-one whose foreign key the
other class has is matched through the property that refers back.

MySQL, and MariaDB before 10.3, do not allow an update or a delete to
select from the table that it modifies. For a join that leads back to
the queried class, these dialects get an UnsupportedOperationException
that says to restrict the query with criteria instead.

Part 8 of the split of apache#16853.
The criteria builder accepted a join type and never used it.
join('club', JoinType.INNER) has had the body of the one-argument join
since it was added, so it set a fetch mode, and a JoinType in the fetch
argument of list matched no fetch mode, so the association was not
fetched at all.

Both now join and fetch the association with the requested type, with
the rules of a where query: a path through a collection restricts the
query with a subquery, and the associations on the path are fetched.
The join types are applied once the criteria are built, so an
association that the criteria have a block for, or join through an
alias, keeps that join. A fetch mode requested afterwards, with join,
select, fetchMode or the fetch argument, replaces the join type.

The sort argument of the list of a criteria query uses a join that the
criteria already have for the association, such as the one of a join
type that the fetch argument requests for it. It joined the association
a second time, which failed with "duplicate association path".

Part 9 of the split of apache#16853.
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.
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.
list, findWhere, findAllWhere, and find and findAll with an example
ignored a JoinType in their fetch argument: they returned the instances
without the association, and list did not fetch it. They now apply it,
before a sort by the association, which uses that join. list fetches
with the requested type, returns each instance once when it fetches a
collection, and applies RIGHT like INNER, since Hibernate does not
support right joins in the criteria queries that list runs.

'join' and 'eager' in the fetch argument of list fetch the association
with a left join and return every instance, as a where query and a
dynamic finder do. list joined it with an inner join without fetching
it, so it left out the instances whose association is null or whose
collection is empty.

The totalCount of a paged list counts each instance once when the list
fetches a collection, and keeps a sort join that hangs under a fetch.

Part 11 of the split of apache#16853.
A sort that starts with the alias that a detached criteria gives the
queried class, as in
new DetachedCriteria(Team, 't').list(sort: 't.name'), was ignored: the
query returned its rows unsorted, without an error. Such a sort now
sorts by the rest of its path, in where queries, detached criteria,
list, the example queries and the sort argument of a criteria query.

Part 13 of the split of apache#16853.
A sort by a property of a collection joined the collection with an
inner join. It left out the instances whose collection is empty, and
took the place of a fetch that the query requested for the collection.
Criteria on a collection with a requested left join initialized the
collection with only the elements that the criteria matched.

- A sort joins a collection with a left join and does not fetch it
  through that join, unless the query asks for the collection to be
  fetched, with or without the sort.
- A left join of a collection that criteria use does not fetch the
  collection. When the query also fetches another collection, that one
  is loaded once the query has run, because Hibernate would read it
  from the columns of the join of the criteria.
- A sort by a collection next to a fetch of another collection repeats
  rows, and a bag cannot tell a repeated row from a repeated element,
  which is why Hibernate does not fetch two bags in one query. When
  either collection is a bag, the query throws an
  UnsupportedOperationException that names both, where it returned the
  bag with repeated elements. A query that projects values loads no
  collection and is not affected.

A fetch that a mapping declares counts as fetched only where Hibernate
joins it: not at or beyond hibernate.max_fetch_depth joins from the
queried class, where Hibernate loads it with a query of its own
(review 5868034911 of apache#16853).

This applies with the grails.gorm.leftJoinAssociationSort setting.
Without it a sort still joins a collection with an inner join, which
leaves out the instances whose collection is empty.

Part 12 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 by the queried class's own alias throws when that alias is also the name of an association.

if (!createdAssociationPaths.containsKey(sortHead)) {
PersistentProperty persistentProperty = entity.getPropertyByName(sortHead);
if (persistentProperty == null) {
String rootAlias = criteria != null ? criteria.getAlias() : detachedCriteria.getAlias();

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.

The query aliases the root as author and sorts by author.author.name. That should sort by the author's name. It throws, because author is treated as the association before it is treated as the root alias. Check the root alias first.

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.

Fixed in 35242f9. The root alias is recognized before looking up a property of the same name, and is stripped once only. The remaining path is then resolved as a property path, so club.club.name means the club association of the root named club rather than stripping club twice.

The new cases cover both an association name and a scalar property name used as the root alias, through the sort argument and a stored sort. All 13 cases of UndefinedAliasSortSpec pass, as does the module codeStyle check.

Resolve an existing association path before stripping a colliding root alias, while retaining the doubled-alias fix. Exercise both compatibility modes and document missing-association rows, counts and invalid remaining properties.

@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 that starts with the alias of the queried class still throws.

}
org.hibernate.sql.JoinType hibernateJoinType = resolveJoinType(joinType);
if (join.criteria != null) {
join.criteria.createAlias(associationPath, join.alias, hibernateJoinType);

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 for Team whose alias is players, sorted by players.team.name, should return the teams. It throws, because players is read as the root alias and team is joined from Team. Follow players to the player, then join team.

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

  1. "Results that change", the note and the skill entry say that a sort that starts with the alias and goes on to an association leaves out the instances without it unless the setting is enabled, and that its count and totalCount do too. They also name the invalid property after the alias, my note 5.
  2. An alias that is also the name of an association sorts by the association again. new DetachedCriteria(Team, 'club').list(sort: 'club.name') returns the 5 teams by the name of their club, as on 7.0.x and with Hibernate 7. James's club.club.name still sorts.
  3. The pull request merges cleanly with 7.0.x and has run ci. The MongoDB functional tests failed in OpenSessionInViewSpec, which waited 10 seconds for the session of an asynchronous request. That spec came with the session fix on 7.0.x (d8c2068), tests no Hibernate code, and passed on every other part of the stack, so a rerun of that job should pass.

Apart from these, my probes from the first review give the same results here as at 16bd465, with the setting off and on. The tests of grails-data-hibernate5-core pass here (1720 tests, 168 skipped), and the guide builds.

Needs a fix

1. James's new comment holds: a path that resolves as an association still loses its first segment when it goes through a collection or through more than one association. The description says that the root alias is stripped only "when the full association path does not resolve". That holds for club.name, but not for these:

7.0.x and this head Hibernate 7, on 8.0.x and at #17079
new DetachedCriteria(Team, 'players').list(sort: 'players.team.name'), also sort('players.team.name') and max: 3 could not resolve property: team of: RjTeam sorts by the team of each player
new DetachedCriteria(Player, 'team').list(sort: 'team.club.name') could not resolve property: club of: RjPlayer sorts by the club of each player's team

Both calls fail on 7.0.x too, so making them work needs no note. But they fail because the alias is stripped from a path that resolves from the queried class. Resolving the whole path, through collections and nested associations, before stripping the alias would make them sort, as Hibernate 7 does.

2. Nothing tracks the Hibernate 7 counterpart. The description says that it's a follow-up to coordinate before the release, but there's no issue or pull request for it. With Hibernate 7, every sort of the first table of my first review still fails: on 8.0.x mostly with a NullPointerException, and at #17079 (1cba001) with IllegalArgumentException: Invalid sort property. Criteria through the root alias of a detached criteria fail with Hibernate 7 as well, as I noted on #17063. An issue for both, named in the description, would keep them from being missed when the stack is merged up.

Smaller points

  • The description still names e359719 as the change to review. 35242f9 and eba8ef9 are part of it too.
  • The imports of AssociationJoinTypeSpec and WhereQueryWithAssociationSortSpec are reordered again here.

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

Merge the reviewed parent fixes and defer collection fetches that would multiply bag elements. Keep requested left joins, complete fetched collections, sort-map joins and distinct static-list results in both compatibility modes.
Merge the reviewed collection-fetch fixes and qualify nested joins through their parent alias. Preserve valid association paths that share the root alias name, with paged, stored and map sorts covered in both compatibility modes.

@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 nested path still drops a team with no players when the left join is named on that path.

if (!joined && !leftJoin) {
// without the leftJoinAssociationSort setting, an association is joined for a sort as it is
// for criteria, with an inner join
join.usedByCriteria = true;

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 for Team whose alias is players, sorted by players.team.name, and fetching players.team as a left join, should include a team with no players. It is left out. 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.

Covered at 060fe905f225, with the lower requested-join fix from 4301e589351c carried through the parent. The exact players.team LEFT-fetch case now has 24 passing variants: colliding root alias and no-alias control, argument/stored/map sorts, paged/unpaged and both settings. The 12 setting-off variants failed before the corrected lower parent was included; no additional alias-runtime fix was needed.

Merge the corrected requested-join parent and preserve implied left collection joins when an example or where-map query sorts a nested fetch path. Retain explicit intermediate join types, path boundaries, complete collections and static-list controls in both compatibility modes.
Merge the corrected requested-join and example-query parent while retaining deferred bag loading and opt-in collection sorts. Keep explicit intermediate joins and pagination safeguards, and align inherited replacement-fetch controls with both compatibility modes.
Merge the corrected collection-sort parent while keeping parent-alias join qualification. Cover the nested LEFT collection path with a colliding root alias and a no-alias control, using argument, stored and map sorts with and without pagination in both compatibility modes.

@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 named with the root alias is missed by a sort that drops that alias.

}
String prefix = associationPath + '.';
for (Map.Entry<String, JoinType> requested : joinTypes.entrySet()) {
if (requested.getValue() == JoinType.LEFT && requested.getKey().startsWith(prefix) && getAssociation(requested.getKey()) != null) {

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 for Team whose alias is t, sorted by t.players.team.name, and fetching t.players.team as a left join, should include a team with no players. It is left out. The sort drops t and does not see the left join. Keep the left join.

@testlens-app

testlens-app Bot commented Nov 25, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 060fe90
▶️ Tests: 61853 executed
⚪️ Checks: 58/58 completed


Learn more about TestLens at testlens.app/docs.

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