Skip to content

Sort by an association with Hibernate 7 as with Hibernate 5, and keep the rows without it with leftJoinAssociationSort - #16863

Open
jdaugherty wants to merge 37 commits into
8.0.xfrom
fix/h7-association-sort-left-join
Open

jdaugherty wants to merge 37 commits into
8.0.xfrom
fix/h7-association-sort-left-join

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

Hibernate 7 counterpart of the Hibernate 5 association-sort parts on 7.0.x: #16853, #17062, #17064 and #17065, and the approved #17070. It matches what those parts do with Hibernate 5 and nothing beyond them.

With GORM for Hibernate 7, a sort by a property of an association, such as Team.list(sort: 'club.name'), read the property through its path, which Hibernate joins with an implicit inner join. The sort left out the instances whose association is null, and the totalCount of a paged list still counted them, so a page of 3 teams had a totalCount of 4. A sort by club.id kept them, because Hibernate reads the id from the foreign key.

What changes:

  • By default, a sort still joins with an inner join, as on 8.0.0, but each association on a sort path is now joined explicitly, and count and the totalCount of a paged list keep those joins, without the ORDER BY. A total therefore counts the rows that the list pages through. This applies to where queries, detached criteria, dynamic finders, criteria queries, list, and findWhere/findAllWhere, which now apply their sort argument as with Hibernate 5. A query with projections is counted with the same joins.
  • With grails.gorm.leftJoinAssociationSort (the setting that Add a setting that keeps the rows without an association when sorting by it #17065 adds for Hibernate 5 on 7.0.x, off by default on 8.0.x, on from 8.1 with GORM: enable leftJoinAssociationSort by default in Grails 8.1 #17164, removed in 9 with GORM: remove the leftJoinAssociationSort compatibility setting in Grails 9 #17165), a sort by an association to a single instance joins it with a left join, so it keeps the instances whose association is null, and the total counts them. The setting does not change a sort by a collection (below); keeping the instances whose collection is empty with the setting, as Sort by and join a collection without changing what a query fetches #17072 does for Hibernate 5, is Hibernate 7: with leftJoinAssociationSort, keep the instances whose collection is empty in a sort by the collection, as #17072 does for Hibernate 5 #17206.
  • A sort by a property of a collection, such as sort: 'scores.score', works as with Hibernate 5: the collection is joined with an inner join, with or without the setting, so the instances whose collection is empty are left out. max and offset page through the rows of the elements, and count and the totalCount count those rows; a list that fetches the collection it sorts by returns and counts each instance once, and since it sorts through the left join of that fetch, it also returns the instances whose collection is empty, with or without the setting. list and a criteria query with an order by the path, such as order('scores.score'), return an instance once for each element, as Hibernate 5 does. An order in the block of the collection, as in scores { order('score') }, returns each instance once, as on 8.0.0, because the block fetches the collection; Hibernate 5 returns it once for each element. A where query, a detached criteria and a dynamic finder return an instance once from the rows that they read. Book.list(sort: 'tags.name') failed with a PathException and now works. An association after a collection on a sort path, as in sort: 'players.contract.salary', is joined with an inner join too, in both modes, in the list and in its count; with the setting on, Hibernate 5 joins that association with a left join and keeps a row for an element whose association is null, which Hibernate 7 cannot do without listing each instance once.
  • A sort by an association that a where query, a detached criteria or a dynamic finder fetches with 'join' or 'eager', or with join('author') on a where query or a detached criteria, uses the left join of the fetch, with or without the setting, so it returns the instances without the association, as a static list with such a fetch already did on 8.0.x, and the count and the totalCount of a page count them too. Hibernate 5 on 7.0.x leaves them out while the setting is disabled, also in a static list, so this goes beyond its parts there; Apply a join type in the fetch argument of list and the example queries #17071 makes its static list keep them. Request JoinType.INNER for the fetch, or with the setting off leave the fetch out, to leave them out as before.
  • Where queries, detached criteria, dynamic finders and criteria queries resolve an order through ExpressionResolver.resolveSort, which reuses a join that the query already has for the association, or a join of the type that the query requests for it, and otherwise joins it as described above. JpaCriteriaQueryCreator assigns the orders after the criteria, so that an order reuses the join of the criteria, which is an inner join by default. HqlListQueryBuilder joins the associations that list sorts through and sorts by the alias of that join. A count keeps the joins of the orders without the ORDER BY: HibernateQuery.clearOrders() keeps the orders it clears for that, as Hibernate 5 keeps the alias that an order joined, so the shared grails.gorm.PagedResultList is unchanged.
  • An order inside an association block of a criteria query, such as club { order('name') }, was ignored. It was added to the criteria of the block, and only the orders of the root criteria reach the query. The builder now moves it to the enclosing criteria when the block ends, as an order by the path through the association, club.name, which sorts through the join of the block, as with Hibernate 5. Orders in the blocks of a detached criteria built in another way, and in the block of an embedded component, are still ignored, as with Hibernate 5 and on 8.0.0.
  • The criteria builder now evaluates the closure of and, or and not itself, as it evaluates every other closure of a criteria query and as the Hibernate 5 builder does. The detached criteria evaluated it, so an association block inside a junction was not a block of the builder, and its orders stayed in the block. A block inside a junction is now the same as a block outside one: its orders keep the place they were declared in, a join type given to it, as in or { club(1) { ... } }, is applied where it was ignored, and its association is fetched with the query.
  • listDistinct selects distinct entities, and SQL rejects an order of a distinct query by a column that is not in its select list. listDistinct { order('club.name') } failed for that reason, and listDistinct { club { order('name') } } would have. When a distinct list is ordered by a value that is not a column of the entity, the query is now built without the SQL keyword and the entities are made distinct once they are read, as Hibernate 5 did for a distinct list.
  • An order by a property that does not resolve, such as order('club.bogus'), failed with a bare AssertionError from Hibernate. It is now rejected with the IllegalArgumentException that list throws for an invalid sort property, as Hibernate 5 rejects it with a QueryException. An order of a block that does not resolve is rejected in the same way; it was left out. A query with a distinct, groupProperty or aggregate projection that a block orders by a value it does not select reaches the database, which rejects it on most databases, as with Hibernate 5.
  • An order by a property that a projection of the query selects with property, distinct or groupProperty sorts by the expression of the projection and not through a join of its own. A distinct or grouped query can only be ordered by what it selects, so projections { distinct('club.name') } with order('club.name') keeps its one join. The same holds when the query selects the association that the property belongs to, as projections { distinct('club') } with order('club.name') does.
  • A sort reuses the fetch join of an association when the query has no other join of it, so fetch: [club: 'join'], sort: 'club.name' joins the club once. list gives the fetch join an alias and sorts through it.
  • HqlListQueryBuilder resolves a sort path in one walk, which validates the path against the mapping and decides where each part is read from. It walked the path once to validate it and once more for the joins.
  • A sort by the identifier of an association that is mapped as a many-to-one, such as club.id, is read from the foreign key without a join, as before this PR, in criteria queries and in list. The mapping of the property decides, because the JPA metamodel reports a hasOne association as a many-to-one too, although its key is in the other table. A sort by contract.id through a hasOne therefore joins the association with a left join.

Fixes next to the sort

This came up while reviewing the sort and is fixed here, as #17067 fixes it for Hibernate 5, since it stood in the way of a sort that the PR documents:

  • An inner join that a query requests for an association to a single instance, with join('club', JoinType.INNER) or fetch: [club: JoinType.INNER], was only applied through the fetch join of a full-entity select. count(), the totalCount of a paged list and a query with projections had no join and counted the instances without the association, so a paged list returned 3 teams with a totalCount of 4. The association is now joined with a plain join in those queries. A requested inner join of a collection is not changed.

Agreement with Hibernate 5

This branch returns the rows that Hibernate 5 returns on 7.0.x for a sort by an association to a single instance and for a sort by a collection, in both modes of the setting, apart from these:

  • A sort by the id of an association, such as Team.list(sort: 'club.id'), reads the foreign key and keeps the instances without the association, as on 8.0.0. Hibernate 5 leaves them out with the setting off, which is GORM for Hibernate 5: a sort by the id of an association leaves out the instances whose association is null #17160.
  • A sort through the fetch of an association, or of the collection that the query sorts by, keeps the instances without it in both modes, as above. With the setting off, Hibernate 5 on 7.0.x leaves them out; a where query on 8.0.0 left them out of its list too, while its total counted them.
  • An order in the block of a collection, players { order('name') }, returns each instance once, as on 8.0.0, where Hibernate 5 returns it once for each element.
  • With the setting on, an association after a collection on a sort path, as above.
  • A static list that sorts by one collection and fetches a bag, as Team.list(sort: 'trophies.title', fetch: [members: 'join']) does with members a Collection, holds each element of the bag once for each element of the sorted collection; on 8.0.0 that sort threw a PathException. A where query, a detached criteria and a dynamic finder already did that on 8.0.0. Apply a requested join type with Hibernate 7 #17079, which is merged together with this pull request, loads such a bag after the query.

Where the two still differ outside this PR's scope, the difference is tracked separately: findAll with an example that sets no property returns null here (#17169), and an or without a criterion, also or { club { order('name') } }, matches no row, as on 8.0.0 (#17208). An association block always joins its association, by default with an inner join, in both modules: with the setting on, Team.withCriteria { club { order('name') } } leaves out a team without a club with Hibernate 5 as well, and club(1) { order('name') } or order('club.name') keeps it.

Not in this PR

Documentation

The "Query Aliases and Sorting" section of the Hibernate 7 where-query docs and the "Association Aliases" section of the criteria docs describe sorting by an association and an order inside an association block. The Grails 8.0.1 section of the upgrade notes and the upgrade skill describe the setting, which rows and totals change in each mode, a sort by a collection, and how to get the previous results.

Tests

AssociationSortSpec, WhereQueryWithAssociationSortSpec and their *LeftJoinSpec subclasses, which run every case with the setting on, cover the sorts through each query API, the totals and counts, sorts by a collection and block orders. ExpressionResolverSpec, HqlListQueryBuilderSpec, JpaQueryContextSpec and CriteriaMethodInvokerSpec cover the joins that a sort makes or reuses and the orders that come out of association blocks.

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.

With GORM for Hibernate 7, a sort by a property of an association read
the property through the association path, which Hibernate joins with
an implicit inner join. The sort left out the instances whose
association is null, while the total count of a paged list still counted
them. A sort must not change which rows a query returns, so each
association on a sort path is now joined explicitly, with a left join
unless the query already joins it or requests another join type for it.

Where queries, detached criteria, dynamic finders and criteria queries
resolve an order through ExpressionResolver.resolveSort, after the
criteria, so that an order reuses the join the criteria have for an
association. list builds its HQL with a left join for each association
it sorts through.

An order inside an association block of a criteria query was ignored,
because only the orders of the root criteria reach the query. It now
moves to the enclosing criteria, qualified with the association.

This is the Hibernate 7 counterpart of #16853 for Hibernate 5.

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

A sort by an ordinary association, including team.club.name and team.club.id, left-joins that association and keeps the rows whose association is null. A restriction that already inner-joins it still drops those rows. Not approving. A distinct projection ordered by the same association builds two joins, and databases reject the order. An alias created inside an association block is prefixed with that association, so the order no longer resolves. A sort through an embedded component, such as details.author.name, still inner-joins the association after the component and drops the rows whose association is null.

A query that selects a property of an association with distinct,
property or groupProperty and sorts by the same property was ordered
through a second join of the association. A database rejects that for
a distinct query, because the order is not in the select list. Such an
order now sorts by the expression that the projection selects.

An order in an association block by an alias that the block declares
was moved to the enclosing criteria as <association>.<alias>.<property>,
which does not resolve. It is now moved as an order by the path that
the alias stands for. An order that names neither a property of the
association nor an alias of the block stays in the block.

A sort through an embedded component, such as details.author.name,
still read the association inside the component through an implicit
inner join, and left out the rows where it is null. The association is
now joined with a left join, in criteria queries and in list.

@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, 6dc070d addresses review 5778258941.

  • Distinct projection ordered by the same association: the order sorts by the expression that the projection selects, so the query has one join and runs again. This also covers property and groupProperty, a nested path, a where query and a criteria query with pagination arguments. Details are in the thread on JpaCriteriaQueryCreator.
  • Alias declared in an association block: the order is moved as the path that the alias stands for, author.publisher.name, and sorts through the join of the alias. An order that names neither a property of the association nor an alias of the block stays in the block. Details are in the thread on CriteriaMethodInvoker.
  • Sort through an embedded component: details.author.name now joins author with a left join and keeps the rows whose author is null, in a where query, a criteria query, a dynamic finder and list, and the totalCount of a paged list matches the list. A where query renders left join author a1_0 on a1_0.id=b1_0.details_author_id, and list builds left join e.details.author s0. A sort by a plain property of the component, such as details.isbn, still adds no join.

AssociationSortSpec has 29 cases now. 13 of the new ones fail on 7c2c241, as do the three new unit cases in ExpressionResolverSpec and HqlListQueryBuilderSpec. Section 90 of the upgrade notes covers the block alias and the component.

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

Sorting by a selected association property, a single block alias, and through an embedded component now keeps the rows whose association is null. Not approving. Ordering inside a plain embedded block throws, and an order that names one of two aliases for the same collection can sort by the other alias.

An order in an association block by an alias that the block declares
was moved to the enclosing criteria as an order by the path that the
alias stands for. When the block declares two aliases of one
collection, each alias has a join of its own, and the sort could use
the join of the other alias. Such an order is now an
AssociationAliasOrder, which keeps its block and the property as the
block names it. PredicateGenerator records the context that the
criteria of a block are built against, and the order is resolved
against that context, so it sorts by the join of the alias it names.

An order in the block of an embedded component threw an
IllegalArgumentException: the property was looked up on the entity of
the criteria of the block, and the class of a component is not a
domain class. It is now looked up on the entity of the association,
and the order sorts by the property of the component.

A sort by a path reused the join that From.getJoins() returned first
for an association, and that set has no order. With two aliases of a
collection, an order by the path of the collection sorted by one alias
at the root and by the other in an association block. A sort now
reuses the first join that the query made for the association, which
is the join that the path shares with its first alias.

@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, 772b853 addresses review 5780261730.

  • Order inside the block of an embedded component: the property is looked up on the entity of the association, so details { order('isbn') } no longer throws and sorts by the embedded value. An order through an association inside the component, details { order('author.name') }, keeps the rows where that association is null. Details are in its thread.
  • Order that names one of two aliases of a collection: the order is no longer rewritten to the association path. It keeps its block and is resolved against it, so order('second.score') sorts by the join of second and order('first.score') by the join of first. Details are in its thread.
  • Order by the path of a collection that has two aliases: found while fixing the previous one. From.getJoins() is a set without an order, so order('scores.score') sorted by first outside a block and by second inside one. A sort by a path now reuses the first join that the query made for the association, which is the join that the path shares with its first alias.

AssociationSortSpec has 46 cases now. 8 of the 17 new ones fail on 6dc070d, as does the new unit case in ExpressionResolverSpec. Section 90 of the upgrade notes and the "Association Aliases" section of the Hibernate 7 criteria docs cover the block of an embedded component and the alias.

The closure of and, or and not in a criteria query is evaluated by the
detached criteria and not by the builder, so an order in an association
block inside a junction stayed in its block and was ignored. The
builder now moves the orders of the blocks inside a junction, at any
depth, to the enclosing criteria once the junction is added. In such a
block createAlias declares an alias with association criteria that
have the alias, and not with a HibernateAlias, and an order by it is
resolved against its block as well.

The upgrade notes now describe a sort by a property of a collection,
and say that the instances without the association can be on the first
page of a paged list and be what first or a findBy finder returns.
An order of an association block had no effect while it stayed in its
block. Moved to the root criteria, it reached queries that can only be
ordered by what they select: listDistinct and queries with a distinct
or aggregate projection ran before and were now rejected by the
database. An order moved out of a block is an AssociationOrder, and in
a query that selects distinct or grouped values or aggregates it is
left out as before, unless the query selects its property.

An order by an alias of a block was sorted by the expression of a
projection that selects the path of the alias, which is the join of
the path and not the join of the alias. Only a distinct or grouped
query has to be ordered by what it selects, so in any other query the
order sorts by the alias that it names.

A sort by the identifier of an association, such as club.id, read the
foreign key column without a join, and now joined the association.
When the association is mapped as a many-to-one, which has its key in
the table of the entity, the path is read as it is again, in criteria
queries and in list. The JPA metamodel reports a hasOne association,
whose key is in the other table, as a many-to-one too, so the mapping
of the property decides.

The join that a sort reuses is read from the joins that Hibernate
keeps in order. The fallback to From.getJoins() was only reachable
from unit specs that mocked From, which now mock Hibernate's types.
The contexts of association blocks are recorded in a map that only the
context of the query creates.
The rules that turn an order of an association block into an order of
the enclosing criteria move to AssociationOrders. The criteria builder
still applies them when a block ends. Criteria that are built in any
other way, such as a detached criteria, keep the orders in their
blocks, and the query now reads them from there, after the orders of
the criteria themselves. An order in a block by an alias of the
criteria around the block is resolved against the block, which sees
that alias, and no longer ignored.

A distinct list ordered by a property of an association was rejected
by the database, since SQL orders a distinct query only by what it
selects. Such a query is built without the keyword and its entities
are made distinct once they are read, as with Hibernate 5. An order of
an association block therefore sorts a distinct list too. An order by
a property that does not resolve is rejected as an invalid sort
property and no longer fails an assertion in Hibernate.

Inside the block of an embedded component, an association block threw
"Not an entity" and createAlias threw "is not a domain class". The
builder takes the managed type and the entity of the component there.

An inner join requested for a to-one association was only applied by
the fetch join of a full-entity select. A count, the total count of a
paged list and a projection query now join the association as well, so
a paged list counts the rows that it returns.

A sort reuses the fetch join of an association when the query has no
other join of it, in criteria queries and in list. HqlListQueryBuilder
validates a sort path and builds its joins in one walk. The methods
that the unit specs call are public, or protected on the method
invoker.
@jdaugherty

Copy link
Copy Markdown
Contributor Author

@jamesfredley, three commits follow 772b853, the one my reply to review 5780261730 describes. They come from a review of my own. The head is 3c54fc5, which also merges 8.0.x.

3ce453a

  • An order in an association block inside and, or or not was still ignored. The closure of a junction is evaluated by the detached criteria and not by the builder, so the builder now moves the orders of the blocks inside a junction once the junction is added.

7f43133

  • Queries that ran on 8.0.x failed on 772b853: with a distinct('name') or max('name') projection, an order of a block reached a query that can only be ordered by what it selects, and the database rejected it. An order of a block is left out of a query that selects distinct values of a property, grouped values or aggregates, unless the query selects its property.
  • With property('owner.scores.score') selected, order('second.score') in the block sorted by the expression of the projection and not by second. Only a distinct or grouped query has to be ordered by what it selects, so in any other query the order sorts by the alias that it names.
  • A sort by club.id read the foreign key without a join on 8.0.x and joined the club on 772b853. It reads the foreign key again, in criteria queries and in list. The mapping of the property decides: the JPA metamodel reports a hasOne association as a many-to-one too, although its key is in the other table, so a sort by contract.id through a hasOne joins the association with a left join.
  • The join that a sort reuses is read from the joins that Hibernate keeps in order. The fallback to From.getJoins() was only reachable from unit specs that mocked From, which now mock Hibernate's types.

fbfbf45

  • An order in an association block of a detached criteria, new DetachedCriteria(Team).build { club { order('name') } }, was ignored and now sorts, after the orders of the criteria themselves. The rules for block orders are in the new AssociationOrders, which the builder and JpaCriteriaQueryCreator share.
  • An order in a block by an alias of the criteria around the block, createAlias('team', 't'); contract { order('t.name') }, was ignored and now sorts by that alias.
  • listDistinct { order('club.name') } failed, because SQL orders a distinct query only by what it selects. A distinct list that is ordered by a value outside the columns of the entity is built without the keyword, and its entities are made distinct once they are read, as with Hibernate 5. An order of a block sorts a distinct list too.
  • order('club.bogus') failed an assertion in Hibernate and is now rejected with IllegalArgumentException: Invalid sort property.
  • Inside the block of an embedded component, an association block, details { author { ... } }, threw "Not an entity", and createAlias threw "is not a domain class". Both work now.
  • An inner join requested for a to-one association, with join('club', JoinType.INNER) or fetch: [club: JoinType.INNER], was only applied by the fetch join of a full-entity select, so a paged list returned 3 teams with a totalCount of 4. count(), the totalCount and a query with projections now join the association as well. A requested inner join of a collection is not changed.
  • A sort reuses the fetch join of an association when the query has no other join of it. HqlListQueryBuilder validates a sort path and builds its joins in one walk.

Section 90 of the upgrade notes covers the changes in results: a sort by a property of a collection, the instances without the association on the first page of a paged list, the requested inner join in counts and projections, and the orders of blocks. The PR description lists every change.

AssociationSortSpec has 79 cases. All specs of grails-data-hibernate7-core pass (459 specs, 4606 tests), run before the merge of 8.0.x; the sort, query and builder specs pass again after it.

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

Not approved. An order in the second of two blocks that share an association name sorts by the first block's join. An order declared inside a junction after a block order is no longer the primary sort. A distinct projection of an association ordered by that association's field still uses two joins.

@borinquenkid

Copy link
Copy Markdown
Member

@jdaugherty I took a look at 3c54fc5, focusing on the part the H2 specs cannot show: whether the SQL you now generate is accepted and correct on the real databases.

I ran seven of the scenarios from AssociationSortSpec against PostgreSQL 16, MySQL 8.0, MariaDB 10.11 and Oracle Free, with H2 as the control: 35 rows, all pass.

  • list sorted by club.name, keeping the team without a club
  • the paged list where totalCount equals what it returns
  • the nested team.club.name sort descending, keeping the player whose team has no club
  • listDistinct ordered by club.name
  • listDistinct ordered by a collection (players.name), listing an instance once
  • a distinct('club.name') projection ordered by club.name
  • groupProperty('club.name') with count(), ordered by club.name

The distinct and group cases are the ones where PostgreSQL and Oracle reject an ORDER BY that is not in the select list, so it is good to see them accepted.

What I did not do: read all 2,977 lines line by line, and run Db2 (the image is amd64 only and I am on arm). CI on this head was still running when I looked, with nothing failing.

The container spec is a throwaway, but it is small. If you want it as a guard I can send it over; it would live next to RLikeHibernate7Spec and use DatabaseContainers.

An order of an association block was resolved by its path from the
root of the query, which does not tell the joins of one block from
those of another. Two blocks of the same association share the join of
that association and each join what is inside it, so an order in the
second block sorted by the join of the first. Every order that comes
out of a block now keeps its block and the property as the block names
it, and is resolved against the context that the criteria of the block
were built against. A sort takes the join that this context tracks for
a path before any other join of the association. AssociationAliasOrder
is removed, since an order by an alias is no longer the only order
that needs its block.

The closure of and, or and not was evaluated by the detached criteria,
so an association block inside a junction was not a block of the
builder, and its orders were added after the orders that were declared
after it. The builder now evaluates the closure of a junction itself,
as it evaluates every other closure of a criteria query. A block
inside a junction is therefore the same as a block outside one: its
orders keep the place they were declared in, a join type given to it
is applied, and its association is fetched with the query.

A distinct projection of an association that is ordered by a property
of the association ran on 8.0.x and was rejected by the database,
because the order had a left join of its own next to the join of the
projection. An order now sorts by the expression of the projection
when the query selects the property or the association that the
property belongs to.
@borinquenkid

Copy link
Copy Markdown
Member

Thanks for the round. I went through the main code (ExpressionResolver.resolveSort, AssociationOrders, HqlListQueryBuilder, JpaCriteriaQueryCreator) and compared the sort entry points on 8.0.x, on your head 3c54fc5 and on Hibernate 5. One thing needs a decision.

list(sort: 'players.name') used to throw a PathException and now works. The entities are made distinct in memory after the SQL limit, so the pages repeat a team. With four teams and max: 2: page 1 is [Chelsea, ManU], page 2 is [Arsenal, Chelsea], page 3 is [Unattached]. Chelsea is on two pages and the pages hold 5 entries while totalCount is 4, which is the invariant this PR is about. Hibernate 5 returns one row per player (5 rows, total 5), so the two versions also differ. Either sorting through a collection should keep failing for a paged list, or the paging needs to happen on distinct entities, or the docs should say so. Which do you want?

The rest matches what I expected: the null team is kept on first, last, where, finders and criteria, the paged total equals the rows returned for to-one paths, and an HQL findAll ignores the sort map exactly as on 8.0.x and Hibernate 5.

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

Not approved. An order that names an alias declared outside the block is dropped when that property is selected. Reusing a detached criteria as a subquery can throw because the block is registered on both queries. The second of two blocks now sorts by its own join, and an order inside a junction keeps its place. Threads PRRT_kwDOAAfRJ860KJxC and PRRT_kwDOAAfRJ860KJxJ resolved.

@borinquenkid

Copy link
Copy Markdown
Member

The consolidation branch, now #16891, merges this PR, and #16889 settled the question your six test cases ran into: blocks of one association with no alias share one join, and an alias after the first for a path has a join of its own, in another block as well.

Your alias-per-block feature is unchanged and passes. The three features for unaliased blocks, which restricted the two blocks to round first and round second, now describe a query that no row can satisfy, since one join cannot be in both rounds. I replaced them with four cases that restrict both blocks to round first and check which join an order sorts by: ascending and descending in the second block, and one each in the first block and a nested block. They keep what the originals tested, that an order inside a repeated block sorts by the join of the blocks.

Say if you would rather keep them another way.

8.0.x now keeps the joins of a query and of its association blocks in
one map by their path, so two blocks of one association share a join.
The four features that expected a join for each block are removed: such
a query now applies the criteria of both blocks to the same join.

The fetch mode join of list is a left join on 8.0.x, so the fetch joins
that a sort reuses are written as left joins.
…nSort setting

A sort by a property of an association changes which instances a query
returns when it joins the association with a left join instead of an
inner join. Following the dev@ discussion of fixes that change results,
that is now behind grails.gorm.leftJoinAssociationSort, the setting that
GORM for Hibernate 5 reads for the same change on 7.0.x. It is disabled
by default, and 8.1 enables it by default.

Without the setting, list, dynamic finders, criteria queries, where
queries and detached criteria join an association that only a sort uses
with an inner join. With it, they join it with a left join.

The specifications of the sorts run with the setting off and on.

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

First round, at c175aca. The branch merges cleanly with 8.0.x at a509055, and CI passed.

I ran the same queries with both modules, with the setting off and on:

  • 90 sorts through every query API;
  • 25 calls of findWhere and findAllWhere;
  • 21 counts and page walks;
  • 12 lists that fetch a bag.

Hibernate 7 ran at this head, on 8.0.x (a509055) and at #17079 (5cdfdac). Hibernate 5 ran on 7.0.x (ffd848b), and at #17070 (e431f96), #17071 (3128803), #17072 (02b0749) and #17073 (c5ae0d7).

A fetched bag holds its elements twice

A list sorted by one collection that fetches a bag fills the bag with each element once for each element of the sorted collection. The fixture has four teams:

  • Full has the members a and b and the trophies t1 and t2;
  • Members has the member c;
  • Trophies has the trophy t3;
  • Empty has neither.

members is a Collection, so a bag, and trophies is a Set. These are the members of Full, the same with the setting off and on:

8.0.x This head #17079 Hibernate 5 on 7.0.x
Team.list(sort: 'trophies.title', fetch: [members: 'join']), also with 'eager' and with max: 2 throws a PathException [a, a, b, b] [a, b] [a, b]
Team.where { name ==~ '%' }.list(sort: 'trophies.title', fetch: [members: 'join']), also a detached criteria and findAllByNameLike [a, a, b, b] the same [a, b] [a, a, b, b]; [a, b] at #17073

The where query, the detached criteria and the dynamic finder already do this on 8.0.x. The static list is new. This PR makes its sort by a collection work, which threw before, and that sort now returns wrong elements.

#17079 loads such a bag after the query and fixes all of these rows. I wouldn't merge this without it. Either take that part of #17079 into this PR for list, or merge the two together.

Differences from Hibernate 5 that the description doesn't list

"Agreement with Hibernate 5" says that this branch returns the rows that Hibernate 5 returns on 7.0.x:

  • for every sort by an association to a single instance, in both modes of the setting;
  • for a sort by a collection, except for an association after a collection with the setting on.

Of my 90 sorts, 68 give the same results as Hibernate 5 at #17070 with the setting off, and 73 with it on. Most of the rest are:

  • ties of the sort;
  • the type of exception for an order that doesn't resolve;
  • a distinct projection ordered by a property of its association, which Hibernate 5 rejects.

These differ in their rows, with the setting off:

Hibernate 5 on 7.0.x Hibernate 5 at #17073 This head 8.0.x
Team.list(sort: 'club.id') the 5 teams with a club the same all 7 all 7
Team.where { name ==~ '%' }.list(max: 10, sort: 'club.name', fetch: [club: 'join']), also with .join('club'), a detached criteria and findAllByNameLike 5, totalCount 5 the same all 7, totalCount 7 5, totalCount 7
Team.where { name ==~ '%' }.list(max: 10, sort: 'players.name', fetch: [players: 'join']) the 5 teams with players, totalCount 7 the same all 7, totalCount 7 5, totalCount 7
Team.createCriteria().list { players { order('name') } } 7 rows, Squad Team 3 times the same the 5 teams with players, once each the same as here
  • The id of an association: this head reads the foreign key and keeps the teams without a club, as 8.0.x does. A where query and Player.list(sort: 'team.club.id') show the same difference. Hibernate 5 leaves them out with the setting off, which is #17160. Hibernate 7 is right here, but the section should name it.
  • A sort through the fetch join of an association: the description and the note say that it keeps the teams without a club, with or without the setting.
    • I'm fine with that result. It's what the fetch asks for, and #17079 does the same for the criteria query.
    • But it goes beyond the Hibernate 5 parts. With the setting off, it changes the rows of a where query on 8.0.x from 5 to 7.
    • The note's "while GORM for Hibernate 5 keeps them only in a static list unless the setting is enabled" holds from #17071 on. On 7.0.x, the static list of Hibernate 5 leaves them out too, even with the setting.
  • A where query that fetches the collection it sorts by: here it sorts through the left join of the fetch. It keeps the teams without players with or without the setting, and lists each team once.
    • Hibernate 5's static list does that from #17071 on. Its where query leaves those teams out with the setting off, also at #17073.
    • The note says that a sort by a collection leaves out the instances whose collection is empty, and that a list that fetches a collection returns and counts each instance once. It could add that a list that fetches the collection it sorts by keeps them.
  • An order in the block of a collection: the rows are those of 8.0.x, since the block fetches the collection and Hibernate lists each team once. The description says that a criteria query returns an instance once for each element, as Hibernate 5 does. That holds for order('players.name'), but not for players { order('name') }.

The setting in the guide

  • whereQueries.adoc says: "With the grails.gorm.leftJoinAssociationSort setting enabled, sorting does not change which rows a query returns". That holds for an association to a single instance. A sort by a collection, or by an association after one, still leaves rows out with the setting, as the upgrade note says further down.
  • The heading of the upgrade note, "A setting makes a sort by an association keep every instance with Hibernate 7", reads the same way. So does its "so that a sort no longer changes which instances a query returns". Until #17206, both could name the association to a single instance.

A junction that holds only a block

Team.createCriteria().list { or { club { order('name') } } } returns no team here. Hibernate 5 returns the 5 teams with a club, sorted by the club.

That's not new. On 8.0.x, an or without a criterion matches nothing: or { } and or { club { } } both return no team. Hibernate 5 matches every row for or { }, and every team with a club for or { club { } }. Now that a block order inside a junction is applied, this case is easier to reach. It doesn't need a change here, but an issue would keep track of it.

Fixed

  • codeconsole's review 6095121552: all three points hold at this head.

    • Team.where { name ==~ '%' }.list(max: 10, sort: 'players.name', fetch: [players: JoinType.INNER]) lists and counts 5 teams. 8.0.x counts 7.
    • sort: 'players.contract.salary', fetch: [players: 'join'] lists and counts 5 teams with the setting off, and 7 with it on.
    • sort: 'root.club.name', fetch: [club: 'join'], its count(), and sort: 'root.club.id' keep the teams without a club, in the list and in its total.
  • Page walks: every page walk reaches every team that the same query returns without paging. I walked pages of 2 of:

    • a where query, a criteria query, list and createAlias, sorted by a collection;
    • a where query sorted by an association after a collection;
    • a where query and list that fetch the collection they sort by;
    • a where query that fetches the club and sorts by it.

    For the last one, 8.0.x has a totalCount of 7, and its pages reach 5 teams.

Smaller points

  • James's block order: I get what jdaugherty measured. Team.withCriteria { club { order('name') } } returns the 5 teams with a club in both modules, in both modes of the setting, and club(1) { order('name') } returns all 7. I agree with leaving it as it is.

  • codeconsole's point 4 in review 6082994813: 8.0.x ignored both of these orders.

    • club { order('bogus') } now fails with an IllegalArgumentException.
    • projections { distinct('name') }; club { order('name') } now fails at the database.

    Hibernate 5 rejects both, and the note says so. I'm fine with that for 8.0.1.

  • join('club') with the setting on: Team.createCriteria().list { join('club'); order('club.name') } leaves out the teams without a club here, as on 8.0.x, because join('club') fetches with an inner join. Hibernate 5 at #17070 keeps them. #17079 makes that fetch a left join.

  • findWhere and findAllWhere: with a sort, they find the same instances as without one, for a club, null, a String for an Integer property and a GString.

  • The paragraph on a block-local sort holds, in both modes, as with Hibernate 5 at #17070:

    • join('team.club', JoinType.LEFT), before or after team { order('club.name') }, keeps the player whose team has no club;
    • JoinType.INNER leaves it out, also for club.id.

What I ran

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

@matrei

matrei commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

A follow-up to my review: the or without a criterion is already tracked, so it needs no new issue.

Only this PR and #17010 together make or { club { order('name') } } return rows and sort them. So whichever of the two merges second could add a test for it.

…le instance

The guide, the upgrade note and the skill entry said that with grails.gorm.leftJoinAssociationSort a sort no longer changes which instances a query returns. That holds for an association to a single instance; a sort by a collection, or by an association after one, still joins with an inner join with or without the setting.

The note also says that a list that fetches the collection it sorts by keeps the instances whose collection is empty, that an order in the block of a collection returns each instance once, as on 8.0.0, and that GORM for Hibernate 5 leaves out the instances without a fetched association while the setting is disabled, also in a static list.

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

@matrei, review 6098316358:

  • The fetched bag: this pull request is merged together with #17079, which loads such a bag after the query, so the static list holds [a, b], as you measured at 5cdfdac. The description says so and lists the static list with a bag among the differences from Hibernate 5 that this pull request has on its own.
  • Differences from Hibernate 5: "Agreement with Hibernate 5" now names the sort by club.id (#17160), the sort through the fetch of an association or of the collection that the query sorts by, and the order in the block of a collection. In bd990f6 the upgrade note says that GORM for Hibernate 5 leaves out the instances without a fetched association while the setting is disabled, in place of "keeps them only in a static list". It also says that a list that fetches the collection it sorts by keeps the instances whose collection is empty, and that an order in the block of a collection returns each instance once, as on 8.0.0. The skill entry says the same. 'an order inside the block of a collection lists each instance once, as the block fetches the collection' in AssociationSortSpec covers the last, with the setting off and on.
  • The setting in the guide: the sentence in whereQueries.adoc, the heading and first paragraph of the upgrade note, the skill entry and the description now say that the setting is for a sort by an association to a single instance, and that a sort by a collection, or by an association after one, joins with an inner join with or without it, until #17206.
  • A junction that holds only a block: #17208.

James's two threads report the block order of PRRT_kwDOAAfRJ86870p7 again. It stays as it is, as with Hibernate 5; the replies say why and which spec checks it.

@Override
D findWhere(Map queryMap, Map args) {
if (!queryMap) return null
if (requestsSort(args)) {

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.

As in PRRT_kwDOAAfRJ86870p7 and the threads before it: the club block is what joins club, and a block joins its association with an inner join unless it asks for another one. The setting only decides the join that a sort makes by itself. Team.createCriteria().list { club { order('name') } } is the query that withCriteria runs, and Hibernate 5 on 7.0.x returns the same rows for it, without the team that has no club. "an order inside an association block of a criteria query sorts by the property of the association" in AssociationSortSpec checks it on c175aca, with the setting off and, through AssociationSortLeftJoinSpec, on. To keep the team without a club, give the block a left join, club(1) { order('name') }, or sort outside the block with order('club.name').

* through the association, as with Hibernate 5, and reuses the join of the block.
*/
private static void moveOrdersOutOf(DetachedAssociationCriteria<?> block, HibernateQuery hibernateQuery) {
String associationPath = block.getAssociationPath();

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 call of PRRT_kwDOAAfRJ86870p7, answered there with Hibernate 5 measured on 7.0.x, and of PRRT_kwDOAAfRJ868_qts: the block joins club with an inner join, as with Hibernate 5, and the setting only decides the join that a sort makes by itself. Nothing in this pull request has changed that since; club(1) { order('name') } or order('club.name') keeps the team without a club.

@jdaugherty
jdaugherty requested a review from matrei November 28, 2026 15:23

@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 find that asks to be read only, and also sorts, can still be written.

@jdaugherty

This comment has been minimized.

@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 62.9127%. Comparing base (58da559) to head (ae85725).
⚠️ Report is 5 commits behind head on 8.0.x.

Additional details and impacted files

Impacted file tree graph

@@               Coverage Diff                @@
##             8.0.x     #16863         +/-   ##
================================================
+ Coverage         0   62.9127%   +62.9127%     
- Complexity       0      27815      +27815     
================================================
  Files            0       2252       +2252     
  Lines            0     112157     +112157     
  Branches         0      20610      +20610     
================================================
+ Hits             0      70561      +70561     
- Misses           0      32185      +32185     
- Partials         0       9411       +9411     

see 2252 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

findWhere and findAllWhere with a sort run as a criteria query, which did not read the readOnly argument, so the instances they returned were written back on flush. The query now applies it, as the HQL query of an unsorted call does.
jdaugherty added a commit to jdaugherty/grails-core that referenced this pull request Nov 28, 2026
matrei
matrei previously approved these changes Nov 28, 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.

Second round, at d61a1e0:

  • bd990f6 changes the guide, the upgrade note, the skill and AssociationSortSpec, as my first review asked.
  • d61a1e0 keeps findWhere and findAllWhere read-only with a sort, which James's review of 15:45 asked for.

The branch merges cleanly with 8.0.x at a509055. AssociationSortSpec passes at this head, with both new features (152 tests, 13 skipped). CI is still running.

Fixed

  • The fetched bag: the description says that this pull request is merged together with #17079, which loads such a bag after the query. It also lists the static list with a bag among the differences that this pull request has on its own. At #17079 the static list holds [a, b].

  • The differences from Hibernate 5: "Agreement with Hibernate 5" names the four that I listed:

    • the sort by club.id (#17160);
    • the sort through a fetch;
    • a list that fetches the collection it sorts by;
    • the order in the block of a collection.

    The upgrade note and the skill entry now describe the last three. The new feature of AssociationSortSpec covers the order in the block of a collection.

  • The setting in the guide: whereQueries.adoc, the heading and first paragraph of the upgrade note, the skill entry and the description say that the setting is for a sort by an association to a single instance.

  • readOnly with a sort: with the teams MU and Arsenal, I read MU from the query, changed its rank, flushed, cleared the session and read it again:

    8.0.x bd990f6 This head Hibernate 5 on 7.0.x
    Team.findWhere([name: 'MU'], [sort: 'rank', readOnly: true]), also with order: 'desc' not written written not written not written
    Team.findAllWhere([name: 'MU'], [sort: 'rank', readOnly: true]) not written written not written not written

Smaller points

  • #17208 is the same case as #17174, which asks what an or without a criterion should mean. #17010 makes Hibernate 7 return what Hibernate 5 returns there, as my comment of 14:52 says. #17208 could be closed for #17174, and the description could name #17174 and #17010.
  • Other queries that ignore readOnly: a where query, and a dynamic finder with a sort, don't apply readOnly in either module, on 8.0.x too. That doesn't come from this pull request.

What I ran

  • AssociationSortSpec: at this head.
  • The readOnly rows: at this head, at bd990f6, on 8.0.x (a509055), and with Hibernate 5 on 7.0.x (ffd848b).
  • The rows of my first review: I didn't rerun them. The code changed since c175aca only in findWhere and findAllWhere.

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 in a block that has no other restriction still drops a team with no club.

// the orders of the block sort the query, in the place they were declared in
moveOrdersOutOf(associationCriteria, hibernateQuery);
}
hibernateQuery.add((Query.Criterion) associationCriteria);

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 setting that keeps a row with no association is on. Team.withCriteria { club { order('name') } } should include Unattached First Team. It is left out, because this adds the block as a restriction after moving the order out. Keep the team.

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.

As in PRRT_kwDOAAfRJ86870p7 and the threads after it: the club block joins club with an inner join, as with Hibernate 5, and the setting only decides the join that a sort makes by itself. matrei measured the same in both modules, in both modes of the setting, in review 6098316358. club(1) { order('name') } or order('club.name') keeps the team without a club.

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

This pull request is open again: it stays separate from #17079, and the two are merged together. The read-only find of James's review 6098836707 is fixed in d61a1e0; the reply is in the thread.

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

Five defects need to be fixed before merging (details inline):

  1. Multi-order collection sorts under leftJoinAssociationSort = true (e.g. order('players.name') followed by order('players.contract.salary')) left-join contract in count()/totalCount while list() implicitly inner-joins it, inflating the count.
  2. HibernateQuery.clone() copies fetchJoinPaths even for projection queries that did not fetch anything, causing totalCount on paged projection queries with fetch: [assoc: 'join'] and a sort to overcount or switch to countDistinct.
  3. JpaQueryContext.isColumnOfRoot returns true for unjoined to-one association paths (embedded component associations like details.author.name and {alias}.club.name), so listDistinct keeps SQL DISTINCT and fails at the database.
  4. Sorted findWhere/findAllWhere drop flushMode, fetchSize, and timeout (only readOnly is forwarded).
  5. JpaCriteriaQueryCreator.isSelected does not strip a leading root. prefix, creating a duplicate join on distinct('club.name') + order('root.club.name').

Simpler/clearer: drop the unused .withConnection(getQualifier()) in HibernateGormStaticApi.whereCriteria, and consider collapsing sortJoins/collectionSortJoins/afterCollectionSortJoins in HqlListQueryBuilder into one map holding alias and join-type metadata.

Path<?> parent = path.getParentPath();
while (parent != null && parent != getRoot()) {
// the path of a collection is joined when it is read, although it is no join of the query
if (parent instanceof Join<?, ?> || parent.getModel() instanceof Attribute<?, ?> attribute && attribute.isCollection()) {

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.

isColumnOfRoot treats any non-collection Path segment that is not a Join as a column of the root table. When resolveSort falls back to a plain Path that crosses a to-one association — such as an association inside an embedded component (listDistinct { order('details.author.name') }) or a {alias}-prefixed association (listDistinct { order('{alias}.club.name') }) — parent is a Path with Attribute.isAssociation() == true that is neither a Join nor a collection. isColumnOfRoot returns true, distinctInMemory stays false, and H2/PostgreSQL reject the SELECT DISTINCT ... ORDER BY query.

Fix: pass endsWithForeignKey into isColumnOfRoot and return false for any parent with parent.getModel() instanceof Attribute<?, ?> attr && attr.isAssociation() except the immediate parent of a foreign-key column (endsWithForeignKey && parent == path.getParentPath()).

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 same on 8.0.x (42951ae): listDistinct { order('details.author.name') } and listDistinct { order('{alias}.club.name') } fail at the database there too, so this pull request leaves them as they are. A sort through an embedded component and a sort by the root alias are outside it, as its description says. listDistinct { order('club.name') }, which failed on 8.0.x, works here.

…of a sorted findWhere

A count joins the rest of a sort path with inner joins after a collection that an earlier order of the count joined, as the list reads it, so two orders through the players count the rows of the list with leftJoinAssociationSort. The count of a page that selects properties no longer joins the associations the query asks to fetch, which its list does not fetch. An order with the root. prefix sorts a distinct query by what it selects. A sorted findWhere or findAllWhere applies flushMode, fetchSize and timeout as an unsorted call does.
@github-actions
github-actions Bot dismissed matrei’s stale review November 28, 2026 23:19

Dismissed automatically: the pull request changed after this approval, from d61a1e0 to ae85725.

jdaugherty added a commit to jdaugherty/grails-core that referenced this pull request Nov 28, 2026
…nto requested join types

The count of a page that selects properties also leaves out the fetches of the query here, since such a list fetches nothing.

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

@codeconsole, review 6100460995: #1, #2, #4 and #5 are fixed in ae85725, each with a feature in AssociationSortSpec that failed before the fix, in the mode you describe. I ran each case on 8.0.x (42951ae) too. #1 and #5 are new with this pull request, with the setting on. #4 came with the sorted findWhere. #2 gave the same totals on 8.0.x, but this pull request says that a total counts the rows that its list pages through, also for a query with projections, so it is fixed here. #3 fails the same way on 8.0.x, as the reply says. whereCriteria no longer calls withConnection(getQualifier()), which nothing read once the sorted findWhere ran its criteria itself. The three join maps of HqlListQueryBuilder stay as they are: merging them is a refactor that this pull request does not need.

James's review 6099657519 reports the block order of PRRT_kwDOAAfRJ86870p7 again. It stays as it is, as with Hibernate 5; the reply is in the thread.

// the orders of the block sort the query, in the place they were declared in
moveOrdersOutOf(associationCriteria, hibernateQuery);
}
hibernateQuery.add((Query.Criterion) associationCriteria);

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.

As in PRRT_kwDOAAfRJ86870p7 and the threads after it: the club block joins club with an inner join, as with Hibernate 5, and the setting only decides the join that a sort makes by itself. matrei measured the same in both modules, in both modes of the setting, in review 6098316358. club(1) { order('name') } or order('club.name') keeps the team without a club.

Path<?> parent = path.getParentPath();
while (parent != null && parent != getRoot()) {
// the path of a collection is joined when it is read, although it is no join of the query
if (parent instanceof Join<?, ?> || parent.getModel() instanceof Attribute<?, ?> attribute && attribute.isCollection()) {

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 same on 8.0.x (42951ae): listDistinct { order('details.author.name') } and listDistinct { order('{alias}.club.name') } fail at the database there too, so this pull request leaves them as they are. A sort through an embedded component and a sort by the root alias are outside it, as its description says. listDistinct { order('club.name') }, which failed on 8.0.x, works here.

@testlens-app

testlens-app Bot commented Nov 29, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: ae85725
▶️ Tests: 97751 executed
⚪️ Checks: 97/97 completed


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. A sort in a block that has no other restriction still drops a team with no club.

// the orders of the block sort the query, in the place they were declared in
moveOrdersOutOf(associationCriteria, hibernateQuery);
}
hibernateQuery.add((Query.Criterion) associationCriteria);

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 setting that keeps a row with no association is on. A list that sorts club by name inside a block should include Unattached First Team. It is left out, because this adds the block as a restriction after moving the order out. Keep the team.

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

One count bug and one inaccurate upgrade-note statement need to be fixed before merging (plus two minor cleanups). Note also that coordination with #17079 remains necessary for static list sorting by a collection while fetching a bag.

return getPath(from, String.join(".", Arrays.copyOfRange(tokens, i, tokens.length)));
}
// the joins after such a collection are made by the sort, as the path of the list reads them
From<?, ?> join = afterCollection ? null : queryJoin(from, tokens[i], 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.

When count() / paged totalCount (joinCollections == true) has multiple orders traversing the same association past a sort-joined collection — e.g. sort: ['owners.scores.score': 'asc', 'owners.scores.round': 'asc'] or order('players.contract.salary'); order('players.contract.version') — the second order reuses the first collection join, sets afterCollection = true on line 211, and then skips existingJoin here on the next segment. That creates a second INNER JOIN on scores (or contract), which for a nested collection produces a Cartesian product and inflates count()/totalCount in both leftJoinAssociationSort modes (e.g. 12 instead of 6 on AssociationSortSpec's league fixture).

Fix: check existingJoin(from, tokens[i]) when afterCollection is true instead of returning null:

From<?, ?> join = afterCollection ? existingJoin(from, tokens[i]) : queryJoin(from, tokens[i], associationPath);

Every join on a sortCollectionJoins join (or its descendants) was created with JoinType.INNER by an earlier order in this count, so this still ignores planned/implicit join types while reusing joins created by earlier orders. Please add regression tests in AssociationSortSpec and ExpressionResolverSpec.

* A sort by a property of a collection, such as `sort: 'tags.name'`, works as it does with Hibernate 5. It joins the collection with an inner join, with or without the setting, and leaves out the instances whose collection is empty. `list` and a criteria query return an instance once for each element of its collection, as with Hibernate 5. A where query, a detached criteria and a dynamic finder return an instance once from the rows that they read; they returned it once for each element. `max` and `offset` page through the rows of the elements, and `count` and the `totalCount` of a paged list count those rows, so a page of a where query can hold fewer instances than its total counts: for two authors with two books each, `Author.where { name ==~ '%' }.list(max: 10, sort: 'books.title')` returns the two authors and a `totalCount` of 4. An association after the collection on the sort path, as in `sort: 'books.publisher.name'`, is joined with an inner join as well, with or without the setting, so a book without a publisher has no row; with Hibernate 5, the setting keeps its row. A list that fetches a collection, the one it sorts by or another one, returns and counts each instance once. A list that fetches the collection it sorts by with `'join'` or `'eager'`, as in `Author.where { name ==~ '%' }.list(sort: 'books.title', fetch: [books: 'join'])`, sorts through the left join of that fetch, so it also returns the instances whose collection is empty, with or without the setting. For paging without repeated instances, sort by a property of the queried class or of a to-one association instead. `Book.list(sort: 'tags.name')` failed with a `PathException` and now works.
* An `order` inside an association block of a criteria query, such as `author { order('name') }`, now sorts the query by that property of the association, through the join of the block, as with Hibernate 5. It was ignored. This also applies inside `and`, `or` and `not`, and the order keeps its place among the orders of the query. The block of a collection, as in `books { order('title') }`, fetches the collection, so such a query returns each instance once, as on 8.0.0, where Hibernate 5 returns it once for each element. An order in a block that names no property of the association now fails with an `IllegalArgumentException`, as it does outside a block. In a query that selects distinct values of a property, grouped values or aggregates, such as a query with a `distinct`, `groupProperty` or `max` projection, most databases reject an order by a value that the query does not select, so such a query with an order in a block now fails at the database, as with Hibernate 5. Both orders were ignored. Remove such an order to get the previous result.
* A query that selects a property of an association with `property`, `distinct` or `groupProperty` and sorts by the same property is ordered by the selected value, as before, and so still returns only the instances that have the association. The same holds for a query that selects the association itself and sorts by one of its properties, such as `distinct('author')` with `order('author.name')`.
* The criteria builder now evaluates the closure of `and`, `or` and `not` itself, as it evaluates every other closure of a criteria query, so an association block inside one of them is the same as a block outside it. A join type given to such a block, as in `or { author(1) { ... } }` for a left join, was ignored and is now applied. To keep the inner join, leave the join type out. The association of such a block is now also fetched with the query, as it is for a block outside a junction, which does not change the instances that the query returns.

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.

"which does not change the instances that the query returns" is inaccurate in two cases now that CriteriaMethodInvoker evaluates junction closures:

  1. A collection block inside and/or/not (e.g. or { players { like('name', '%') } }) now calls hibernateQuery.join(..., JoinType.INNER), adding the collection to fetchJoinPaths and causing applyRequestedJoins to root.fetch(...) it. Hibernate 7 deduplicates roots on a collection fetch, so each root is now returned once instead of once per matching element as on 8.0.0.
  2. A self-referential association block inside a junction now hits CriteriaMethodInvoker's associationClass.equals(oldTargetClass) branch and defaults to JoinType.LEFT instead of JoinType.INNER, retaining rows whose self-association is null.

Please update this sentence to reflect those changes.

* A sort path without the {@code root.} prefix, which names the queried class, as the sort of a list reads it.
*/
private static String withoutRootPrefix(String propertyName) {
return propertyName.startsWith("root.") ? propertyName.substring(5) : propertyName;

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.

Optional cleanup: unlike ExpressionResolver.resolveSort (line 173), withoutRootPrefix does not guard against propertyName == null, so an order with a null property throws NullPointerException instead of IllegalArgumentException("Invalid sort property").


def "test a sort path that ends with a foreign key is not joined for it"() {
given:
def root = Mock(From)

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.

Optional cleanup: root and context here are unused (lines 339–340 create sqmRoot and sqmContext instead).

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

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants