Skip to content

Keep the root alias of a detached criteria in the count of a paged list - #17063

Open
jdaugherty wants to merge 7 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-03-paged-count-root-alias
Open

jdaugherty wants to merge 7 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-03-paged-count-root-alias

Conversation

@jdaugherty

Copy link
Copy Markdown
Contributor

Description

Part 3 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 #17062. Until that merges, this pull request also shows the commits below it. The change to review is the last commit, 62bf8ed.

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.

Results that change

  • What changes: The totalCount of a paged list of a detached criteria that names the queried class with an alias and has criteria through that alias.
  • How to get the old result: There is none: the count failed or did not match the list.
  • Setting: No setting.

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

Verification

The association sort and join specs of grails-data-hibernate5-core pass on this branch, with grails.gorm.leftJoinAssociationSort off and on, and codeStyle passes for the touched modules. The full build was not run locally.

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

@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. The total of an unaliased page changes when the sort joins an association the call asked to keep.

if (currentAlias != null && i == tokens.length - 2 && isForeignKeyIdentifier(currentEntity, association, tokens[i + 1])) {
return currentAlias + '.' + token + '.' + tokens[i + 1];
}
CriteriaAndAlias criteriaAndAlias = getOrCreateAlias(associationPath.toString(), generateAlias(token));

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.

Two teams match. One has no club. The page asks for a left join of club and sorts by club.name. The total used to be 1. It is now 2, because the count copies the left join. Keep the count the sort used to produce.

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.

I would keep the requested LEFT join in the count. Mattias checked this case on the parent PR and confirmed that it belongs on 7.0.x under the combined dev@ rule: #16853 (comment).

The call explicitly requests LEFT. The old sort overrode that request with an inner join; the corrected list and totalCount must both include the team without a club. Keeping the old count while returning the corrected list would make them disagree. This is different from changing an implicit sort join, which stays behind leftJoinAssociationSort. Request INNER, or add a non-null criterion, to retain the old rows.

That behavior is inherited from part 1. This part fixes the root alias on the count copy; it should not undo the explicit-join fix.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed at 62bf8ed (base 7.0.x), the last commit. I probed paged lists and their totalCount at 7.0.x, at part 2 (279520e) and here, with a team without a club among three that match.

The fix is right. Without an alias, CriteriaImpl holds Hibernate's root alias this, which createCriteria(entityName) uses anyway, so the copy only changes for a query through an alias of the queried class:

new DetachedCriteria(Team, 't') 7.0.x and part 2 This head
.eq('t.name', 'Arsenal First Team').list(max: 2) throws could not resolve property: t 1 row, totalCount 1
.like('t.name', '%First%').list(max: 2, sort: 't.name') throws 2 rows, totalCount 3
.like('t.name', '%First%').join('club', JoinType.LEFT).list(max: 10, sort: 'club.name') throws 3 rows, totalCount 3
.like('name', '%First%').list(max: 2), alias unused 2 rows, totalCount 3 the same

The where queries and the detached criteria without an alias that I probed give the same rows and totals at part 2 and here.

Needs a fix

1. The description promises a note that isn't there. It says the upgrade guide has a note under Grails 7.0.18 and the upgrade skill the same entry, but the commit has neither. By #17061, a fix that makes a failing call work is a bug fix like any other, so it doesn't need them. Please drop that sentence and the "Results that change" section. The section also says the count "did not match the list", but I found no case where the count ran and differed from the list, at 7.0.x or here. If you have one, the note is needed after all.

2. Add run ci, as on #17062: the test jobs were skipped.

Notes

  1. On James's comment: the total of Team.where { name ==~ '%First%' }.join('club', JoinType.LEFT).list(max: 10, sort: 'club.name') does go from 2 to 3. The list goes from 2 rows to 3 with it, though, so the count agrees with the list. Both change in part 1 (#16853), not in this commit:
7.0.x #16853 Part 2 This head
list 2 3 3 3
totalCount 2 3 3 3

Whether the list should keep that team is a question for #16853, which I've answered there: the change stays, with a note under 7.0.18.

  1. With Hibernate 7 on 8.0.x (0518f48), criteria through the root alias of a detached criteria fail before any count runs: eq('t.name', …) throws Cannot use comparison criteria on non-existent property [t.name], and with sort: 't.name' the list throws a NullPointerException. After the merge-up the call works with Hibernate 5 only, which is no reason to hold this. Hibernate 7 needs an issue of its own, together with part 13's sort through the root alias.

Verified as correct

  • The new feature fails at part 2 with could not resolve property: t and passes here.

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: No status

Development

Successfully merging this pull request may close these issues.

3 participants