Skip to content

Fix root alias registration and nested alias path resolution in subqueries - #16821

Open
borinquenkid wants to merge 21 commits into
fix/datastore-wherelazy-thread-safe-8.0.xfrom
fix/h7-subquery-root-alias-nested-paths-8.0.x
Open

borinquenkid wants to merge 21 commits into
fix/datastore-wherelazy-thread-safe-8.0.xfrom
fix/h7-subquery-root-alias-nested-paths-8.0.x

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Fixes #16813

Chained on #16820 (chain: #16816, #16817, #16818, #16820). no ci until the chain reaches 8.0.x.

Problem

On Hibernate 7, a subquery that is correlated on the root alias of the enclosing query lost the correlation: Team.where { def t = Team ... exists(Club.where { id == t.club }...) } and the nested path t.club.id either dropped the comparison or threw. The outer query then returned rows it should not have.

Changes

  • JpaCriteriaQueryCreator registers the root alias a criteria declares for its own root in JpaQueryContext, for the query and for each subquery. Hibernate 5 already correlates id == t.club, so this is Hibernate 7 only.
  • Outside a subquery, a property named through the root alias, as in new DetachedCriteria(Book, 'b').eq('b.title', ...), resolves in restrictions, projections, sorts and the totalCount of a paged list (part of Hibernate 7: resolve the root alias in detached-criteria sorts and restrictions #17167). A join type requested for a path now applies to a sort that names the path through the alias. When the alias is also the name of a property, that name and a path through it stay the property. updateAll and deleteAll do not accept the alias, and count ignores a sort with or without it.
  • DetachedCriteriaTransformer resolves a nested alias path (t.club.id) to its root alias when the chain starts at a declared alias; a chain that starts at a method call or an undeclared variable stays eq. It is in grails-datamapping-core, which Hibernate 5 shares: the same fix for Hibernate 5 is proposed against 7.0.x in its own pull request.
  • PropertyComparisonCriterionHandler compares an association with a value that is not an entity (id == t.club, eqProperty('club', 'id')) by its identifier, as Hibernate 5 does. Two associations are compared as entities, as on 8.0.x. Comparing two associations of unrelated classes follows in its own pull request on this one.
  • refactor(hibernate7): drop the PredicateGenerator handler registrations the superclass lookup covers #16921, squash-merged into this branch, drops the PredicateGenerator registrations that the superclass lookup covers.
  • Example-app scenario specs on Hibernate 5 and 7 (SubqueryAliasScenarioSpec) run the root alias subqueries end to end.

The merge commits of #16816 and #16820 into this branch contain conflict resolutions; the one that had added code in neither parent (null filtering for a function's in list) is reverted in the last commits, so the tree has nothing that is in neither of them.

What changes for applications on 8.0.x

A subquery that compared with an association of the enclosing root alias (id == t.club) was dropped on 8.0.x, so the outer query returned rows it should not have. It now restricts them, as on Grails 7. That old result contradicts the query, so there is nothing to keep it for, but it changes results and has a note in the Grails 8.0.1 upgrade section. t.club.id and an association compared with an identifier threw and now run.

Tests

DetachedCriteriaRootAliasSpec runs each call with and without the root alias, and the paths whose first name is also the alias. 8 of its rows failed before the last two commits. The Hibernate 7 module (5509 tests) and codeStyle pass on the head.

SubqueryAliasSpec, WhereQueryPropertyAliasSpec and the scenario specs; Hibernate 7 core, datamapping-core-test and datastore-core pass with 0 failures at this head.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

Copilot AI balanced review requested due to automatic review settings November 1, 2026 18:22

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

…eries

- Register root alias in JpaQueryContext during createQuery() and populateSubquery() in JpaCriteriaQueryCreator so correlated subqueries can resolve outer root aliases
- Walk nested PropertyExpression chains to the root VariableExpression via aliasRootName() in DetachedCriteriaTransformer when rewriting alias property comparisons
- Preserve alias in AbstractDetachedCriteria.clone() and read effective.alias in DetachedCriteria.withPopulatedQuery() for derived and whereLazy queries
- Add unit and subquery alias specifications

Fixes #16813
…in property comparisons, as Hibernate 5 does

id == t.club in a correlated subquery worked on H5 and failed on H7 with
'Cannot compare Long with ScenarioOwner'. The H7 spec had been rewritten to
t.club.id, which hid the difference.

Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
@borinquenkid

Copy link
Copy Markdown
Member Author

Added integration scenarios for correlated subqueries (SubqueryAliasScenarioSpec) to both grails-test-examples/hibernate5/grails-hibernate and hibernate7/grails-hibernate.

Two things for the team:

  1. Fixed in H7 to match H5: id == t.club (an id compared with an association of the root alias) works on H5 and failed on H7 with Cannot compare Long with ScenarioOwner. H7's own SubqueryAliasSpec had been rewritten to t.club.id, which hid it. PropertyComparisonCriterionHandler now compares by the association's identifier, and the original form is back in that spec.
  2. H7 only: a nested alias path through an association (name == i.owner.name) works on H7 (this PR). H5 rejects it with could not resolve property: i. It is in the H7 scenario spec only. It is an addition, not a behaviour change.

@borinquenkid

Copy link
Copy Markdown
Member Author

Started the one CI run of the stack on this head (6a8e77d): no ci removed, run ci added, because the base is a side branch. It runs #16818, #16820 and this repair together, as matrei asked.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

# Conflicts:
#	grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/FunctionCallingCriterionHandler.java
#	grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PropertyCriterionHandler.java
#	grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/query/jpa/JpaQueryBuilder.java
@borinquenkid

Copy link
Copy Markdown
Member Author

The run on 6a8e77d is cancelled: it would have failed on the Hibernate 7 ne scenario that #16816 now marks pending. This head (8142212) merges #16816's current head, keeps #16817/#16818's null filtering for in on a function, and drops the @PendingFeature on SubqueryAliasSpec "Test subquery with root alias", which passes with this repair. datastore-core, datamapping-core, Hibernate 5 core and Hibernate 7 core pass locally, and so do the ne example spec and codeStyle. This push starts the one CI run of the stack.

@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. Two associations whose identifiers hold an association to unrelated classes are still compared as entities.

List<Predicate> parts = new ArrayList<>();
for (int i = 0; i < leftParts.size(); i++) {
parts.add(negate ? criteriaBuilder.notEqual(leftParts.get(i), rightParts.get(i)) :
criteriaBuilder.equal(leftParts.get(i), rightParts.get(i)));

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.

Left and Right both use a composite identifier whose first part is an association to a different class. eqProperty('left', 'right') should compare the identifier columns. It throws, because those association parts are compared as entities. Compare those parts by their identifiers too.

@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 8142212 (base fix/datastore-wherelazy-thread-safe-8.0.x, #16820's head branch, at ef5bdda). CI ran on this head and passed: that is the one run of the whole stack asked for on #16816 and #16820.

GitHub shows 268 changed files because this branch has #16816's current head, with today's 8.0.x, and #16820's branch does not. Measured against #16820 merged with #16816's head, this PR changes 11 files: JpaCriteriaQueryCreator, PredicateGenerator, PropertyComparisonCriterionHandler, DetachedCriteriaTransformer, FunctionComparison (item 2) and six specs. Merging #16816's head into #16820's branch would bring the diff here down to them.

What I ran locally:

  • The new specs on #16820 merged with #16816's head (the conflicts resolved as in e4e3278): all six SubqueryAliasSpec features, all five SiblingAssociationPropertyComparisonSpec features and the two nested-path features of WhereQueryPropertyAliasSpec fail there, so they guard the change.
  • The same Hibernate 7 specs on today's 8.0.x (9fc7dd3). In "Test subquery comparing an id with an association of the root alias", id == t.club && name == "Manchester United" returns both teams, so the comparison is dropped. The t.club.id features throw MissingPropertyException: No such property: club for class: Team. The five sibling features throw SemanticException: Cannot compare left expression of type ....
  • 7.0.x with Hibernate 5 (item 1).
  • A throwaway spec for comparing two associations to unrelated classes, on this head, on 8.0.x and on Hibernate 5 (item 3).

Needs a fix

  1. Branch: the nested alias path fix belongs on 7.0.x as well. DetachedCriteriaTransformer is in grails-datamapping-core, which Hibernate 5 shares, and 7.0.x has the same check. There, on Hibernate 5, exists(Club.where { id == t.club.id && name == "Manchester United" }.property('name')) inside Team.where { def t = Team ... } throws MissingPropertyException: No such property: club for class: grails.gorm.tests.Team: the transform leaves t.club.id as a Groovy expression on the class. With this PR's change to the transform applied to 7.0.x, the query returns the right team. grails-datamapping-core still passes, and grails-data-hibernate5-core has no new failures. A call that throws is a bug that goes to the oldest branch that has it, by the rule in the dev@ thread. A small PR against 7.0.x, with the change to the transform, the two nested-path features of WhereQueryPropertyAliasSpec and a Hibernate 5 feature (the last feature of your Hibernate 5 SubqueryAliasScenarioSpec is one), would bring the fix to Hibernate 5 applications on 7.x once merged up. This PR keeps the Hibernate 7 parts. The root alias registration is needed on Hibernate 7 only: on 7.0.x, Hibernate 5 already correlates id == t.club.

  2. The merge commit e4e3278 adds code that is in neither parent. Resolving the conflict with #16816, it adds two changes that neither #16816 nor #16820 has: FunctionComparison now leaves null out of the list of an in on a function, and FunctionCallingCriterionHandler returns a disjunction for an empty list. That is #16818's null filtering for a function's list, moved out of #16818's handler and into FunctionComparison. JpaQueryBuilder uses that class too, so the change also reaches the bulk statements of Hibernate 5 and Hibernate 7. It belongs in #16816, where #16818 now is: the FunctionCallingCriterionHandler conflict was resolved there by keeping #16816's version, without the filter. James's open point on #16816 also applies to it: !(qty in [1, null]) should match no rows, as SQL NOT IN with a null does, and leaving the null out matches the row with 2. At this head, !(upper(name) in ['A', null]) matches the row whose name is b, just as !(name in ['a', null]) does. Whatever #16816 decides for a plain in, a function's list should follow it there, in a commit that gets reviewed. The merge here should take #16816's version of both files.

  3. Two associations to unrelated classes: the parts of a composite id are paired by name, and an association part still throws. identifierParts sorts the properties of a composite id by name, and compareIdentifiers pairs the two lists in that order. When the two ids have different property names, the parts are paired wrong without an error. With id composite: ['country', 'city'] on one side and id composite: ['nation', 'town'] on the other, eqProperty('left', 'right') compares city with nation and country with town. (SE, Lund) against (SE, Lund) does not match, and (SE, Lund) against (Lund, SE) does. Hibernate 5 pairs the columns in the declared order and returns the first. James's point from today is a second gap in the same code: when a part of the composite id is an association, and the two sides' associations go to unrelated classes, it still throws SemanticException: Cannot compare left expression of type 'OwnerA' with right expression of type 'OwnerB'. Hibernate 5 compares the foreign key columns there and returns the row.

    #16813 does not need this comparison. id == t.club and eqProperty('plainLeft', 'id') go through identifierIfCompared, which compares an association with a value that is not an entity. Two associations to unrelated classes throw on 8.0.x today, so nothing is lost if they wait. I'd take unrelatedEntities, compareIdentifiers and their features out of this PR and into one of their own. That PR would pair the parts in the declared order (GORM's composite identity keeps it; the JPA metamodel does not) and compare an association part by its identifier, so this PR no longer waits on them. Keep the !isEntityValued(other) guard from 8052e93, so that two associations are compared as entities, as on 8.0.x. If the comparison stays here instead, both gaps need fixing before this lands. In that case, also note that for neProperty this head is true when any part differs, which is what the call asks for, while Hibernate 5 ANDs the column comparisons and is true only when every part differs. The Javadoc's "This is what Hibernate 5 does" would need to say which one this does.

  4. Description. Please rewrite it to match this head:

    • It says the PR keeps the alias across clone() and withPopulatedQuery. That is in #16820 now (clone() copies the alias there), and this PR does not touch AbstractDetachedCriteria.
    • It leaves out four things: an association compared with a value that is not an entity (id == t.club, eqProperty('club', 'id')) is now compared by its identifier; two associations to unrelated classes are compared by their identifiers (if that stays); #16921, squash-merged into this branch, drops the PredicateGenerator registrations; and the example-app scenario specs on Hibernate 5 and 7.
    • What changes for applications on 8.0.x, as the rule in the dev@ thread asks. A subquery that compares with an association of the enclosing query's root alias (id == t.club) was dropped on 8.0.x, so the outer query returned rows it should not have. It now restricts them, as on Grails 7. That old result contradicts the query, so there is nothing to keep it for, but it changes results, so it needs a line in the upgrade notes. t.club.id, and an association compared with an identifier, threw and now run.

Note

  1. PredicateGeneratorHandlerRegistrySpec (from #16921) reads the private BUILTIN_HANDLERS map and calls the private findHandler by reflection, where the repository's rule is to test through public APIs. Its "is registered only when its handler differs from its ancestor" feature pins how the map is laid out rather than what a query does: registering a subclass with its ancestor's handler would fail it and change no query. The rest of the suite runs every criterion type through queries, so I would drop that feature at least.

Verified as correct

  • registerRootAlias registers the alias a criteria declares for its own root, for the query and for each subquery. A subquery's context resolves through its parent, so t in a subquery finds the enclosing root, and a nested subquery's own alias (subClub) is found before its parent's.
  • aliasRootName follows the chain to its first element and rewrites the comparison only when that element is a declared alias. A chain that starts at a method call, or at a variable that is not an alias, still becomes eq.
  • Every criterion class of Query still gets the handler it had before the registrations were dropped: the table in PredicateGeneratorHandlerRegistrySpec passes on the base as well.
  • Two associations to subclasses of one hierarchy (eqProperty('dog', 'cat')) still compare as entities, with the same result as on 8.0.x and on Hibernate 5.

…p the registry layout feature

The merge of #16816 had added null filtering for a function's in list and a disjunction for an empty one in
FunctionComparison and FunctionCallingCriterionHandler. Neither parent has it, so it goes back to
#16816's version of both files; a function's list follows whatever #16816 decides for a plain in.

PredicateGeneratorHandlerRegistrySpec no longer has the feature that pins how the registration map is laid
out, which no query depends on.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…ns out of this branch

The identifier comparison for eqProperty/neProperty of two associations to unrelated classes pairs the
parts of a composite identifier by name and throws for an association part. It follows in its own pull
request on this one; this branch keeps the guard that two associations are compared as entities, as on
8.0.x.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

Thank you. Pushed and changed:

  1. The merge's extra code is gone: FunctionComparison and FunctionCallingCriterionHandler are fix(hibernate7): support where-query functions and refactor PredicateGenerator #16816's versions again. A function's in list will follow whatever fix(hibernate7): support where-query functions and refactor PredicateGenerator #16816 decides for a plain in, in a commit that gets reviewed there.
  2. unrelatedEntities, compareIdentifiers and their feature are out of this branch; the !isEntityValued(other) guard stays. They move to their own pull request on this one, with the declared-order pairing, the association part and the neProperty Javadoc from your review.
  3. The description is rewritten to match this head, with what changes for applications, and the 8.0.1 upgrade section has a note for the id == t.club change.
  4. The feature that pins the layout of the registration map is dropped; the table of handlers per criterion stays.

Item 1, the 7.0.x pull request for the nested alias path, comes next; I'll link it here.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@borinquenkid

Copy link
Copy Markdown
Member Author

The 7.0.x part (item 1 of your review) is #17060: the transformer change, three features of WhereQueryPropertyAliasSpec and a Hibernate 5 spec that reproduces the MissingPropertyException. Once it is merged and merged up, the transformer change drops out of this PR's diff.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@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. Two associations whose identifiers hold an association to unrelated classes are still compared as entities.

otherPropertyPath = right;

if (c instanceof Query.EqualsProperty) {
return criteriaBuilder.equal(propertyPath, otherPropertyPath);

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.

Left and Right both use a composite identifier whose first part is an association to a different class. eqProperty('leftRef', 'rightRef') should compare the identifier columns. It throws, because those parts are still compared as entities. Compare those parts by their identifiers too.

… in) into fix/h7-subquery-root-alias-nested-paths-8.0.x

# Conflicts:
#	grails-doc/src/en/guide/upgrading/upgrading80x.adoc
@borinquenkid

Copy link
Copy Markdown
Member Author

Merged #16820's branch (fb22058, which carries #16816 with 8.0.x merged in) into this one, so this branch has the null handling of #16816 and the materializeLazyCriteria() of #16820. The only conflict was two independent notes in upgrading80x.adoc; both are kept. The Hibernate 7 module (5417 tests), grails-datastore-core (494) and grails-datamapping-core (1891) pass, and so does codeStyle. James, the comparison of two associations to unrelated classes whose composite identifier holds an association follows in its own pull request on this one; I will link it here.

@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley the comparison of two associations whose composite identifiers hold an association to unrelated classes is in its own pull request on this one: #17154. eqProperty('leftRef', 'rightRef') now compares those parts by the identifier of the associated entity, one part at a time; the two new rows fail without the change.

borinquenkid added a commit that referenced this pull request Nov 23, 2026
 and #16820) into fix/h7-bulk-write-pagination-guard-8.0.x

# Conflicts:
#	grails-doc/src/en/guide/upgrading/upgrading80x.adoc
#	grails-skills/upgrade-guide-8/skills/grails-8-upgrade/SKILL.md

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

@borinquenkid #16863 and #17079, the Hibernate 7 counterparts of the association-sort and requested-join parts on 7.0.x, are now narrowed to what those Hibernate 5 parts do, and the root alias of a detached criteria is outside them. One merged Hibernate 5 part depends on it, though: #17063 keeps the root alias of a detached criteria in the count of a paged list. With Hibernate 7 such criteria fail before the count runs, as #17167 describes:

new DetachedCriteria(Book, 'b').eq('b.title', 'Example').list(max: 2).totalCount
new DetachedCriteria(Book, 'b').list(sort: 'b.title')

This PR registers the root alias that a criteria declares in JpaQueryContext, for the query and for each subquery. Could it cover these top-level cases too, at least the restriction and the paged count that #17063 needs, with specs for them? If that is too far from #16813, say so, and #17167 stays the place for it.

… queried class

A join type requested for a path was not applied to a sort that named the path through the root alias, so it
left out the instances without the association. A path through an association with the same name as the root
alias resolved against the root and returned other rows.

Part of #17167

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… in the join plan

The upgrade note says that a property of the same name as the root alias keeps its meaning.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jdaugherty Yes, it is covered here now. Both of your calls, the restriction with its paged totalCount and the sort, already worked through the root alias registration of this pull request. Two related cases did not, and 91902b5 fixes them:

  • a join type requested for a path, as with list(sort: 't.club.name', fetch: [club: JoinType.LEFT]), was ignored when the sort named the path through the alias;
  • with an alias that is also an association name, as in new DetachedCriteria(Team, 'club'), club.name resolved against the team.

DetachedCriteriaRootAliasSpec runs your calls and the restrictions, projections and sorts that matrei listed on #17167, each with and without the alias.

Not covered, so #17167 stays open: updateAll and deleteAll with the alias, and count joining a sorted association, which #17079 does. These commits add JoinPlanner to the files that conflict with #17079.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@testlens-app

testlens-app Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

🔎 No tests executed 🔎

🏷️ Commit: 91902b5
▶️ Tests: 0 executed
⚪️ Checks: 44/44 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.

5 participants