Skip to content

Fix for when H7 createAlias joins the association twice, and ignores the join type for the alias - #16573

Merged
jdaugherty merged 1 commit into
apache:8.0.xfrom
ruthst00:fix/16562-h7-create-alias
Nov 4, 2026
Merged

jdaugherty merged 1 commit into
apache:8.0.xfrom
ruthst00:fix/16562-h7-create-alias

Conversation

@ruthst00

Copy link
Copy Markdown
Contributor

Description

Root cause: Alias discovery discarded the requested join type, and alias resolution created a new join instead of reusing the association-path join.

Changes

  • Preserve the configured join type.
  • Reuse the same join for association paths and aliases, including predicates, projections, and ordering.
  • Add regression coverage for duplicate rows/counts, inner and outer joins, detached criteria, and subqueries.
  • Update the public criteria documentation.

Validation

  • Full Hibernate 7 core suite: 3,574 passed, 0 failed, 45 skipped.
  • Production Checkstyle and CodeNarc passed; test-source style tasks were skipped by configuration.
  • Repository conventions and git diff --check passed.

Fixes #16562

Generated with GPT 6 Astra via Cline API Provider in IntelliJ IDEA 2025.3.3

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.

@borinquenkid

Copy link
Copy Markdown
Member

Thanks for the fix. Reading JpaCriteriaQueryCreator as a whole, the alias handling is the part that is hard to test, and I think it should move into a class of its own. Three things in the current shape:

  • createQuery() and populateSubquery() repeat the same thirteen lines (lines 105-117 and 167-179): gather the explicit aliases from the HibernateQuery and from the HibernateAlias criteria, build the JpaQueryContext, registerDetachedJoins, discoverAliases.
  • discoverAliases is private and recursive, and its behavior (which join type an alias gets, when a dotted property name implies an alias) can only be observed by building a whole query against a database. The new CreateAliasJoinSpec has to do exactly that.
  • assignCriteria calls discoverAliases a second time on the same criteria. It is harmless because of the hasAlias guards, but the DetachedAssociationCriteria branch has no guard, and a separate class makes that visible.

Proposal, behavior unchanged: a package-private class that owns the alias registration for one detached criteria.

package org.grails.orm.hibernate.query;

/**
 * Collects the aliases of a criteria query and registers them in its {@link JpaQueryContext}: the aliases made with
 * {@code createAlias}, the joins requested on the detached criteria, the aliases of association blocks and the
 * aliases implied by a dotted property name.
 */
final class QueryAliasRegistrar {

    private final DetachedCriteria<?> detachedCriteria;
    private final HibernateQuery hibernateQuery; // null for a detached criteria without a query

    QueryAliasRegistrar(DetachedCriteria<?> detachedCriteria, HibernateQuery hibernateQuery) {
        this.detachedCriteria = detachedCriteria;
        this.hibernateQuery = hibernateQuery;
    }

    /** The context of the query or subquery over {@code root}, with every alias of this criteria registered. */
    JpaQueryContext createContext(JpaQueryContext parent, Root<?> root) {
        JpaQueryContext context = JpaQueryContext.forSubquery(parent, explicitAliases(), root);
        registerDetachedJoins(context);
        discover(detachedCriteria.getCriteria(), context);
        return context;
    }

    List<HibernateAlias> explicitAliases() {
        List<HibernateAlias> aliases = new ArrayList<>();
        if (hibernateQuery != null) {
            aliases.addAll(hibernateQuery.getAliases());
        }
        for (Query.Criterion criterion : detachedCriteria.getCriteria()) {
            if (criterion instanceof HibernateAlias ha) {
                aliases.add(ha);
            }
        }
        return aliases;
    }

    void registerDetachedJoins(JpaQueryContext context) {
        detachedCriteria.getJoinTypes().forEach((path, joinType) ->
                context.registerAlias(path, new HibernateAlias(path, path, joinType)));
    }

    void discover(List<Query.Criterion> criteria, JpaQueryContext context) {
        // the body of discoverAliases as it is in this PR, with detachedCriteria taken from the field
    }
}

JpaCriteriaQueryCreator then keeps one field, private final QueryAliasRegistrar aliases; built in the constructor, and:

Root<?> root = cq.from(javaClass);
context = aliases.createContext(parentContext, root);          // createQuery()
...
context = aliases.createContext(parentContext, root);          // populateSubquery()
...
aliases.discover(criteriaList, context);                       // assignCriteria()

That removes the duplicated block and both private methods from the creator, and the alias rules become unit-testable with a Mock(JpaQueryContext), no database, for example:

def "a join requested on the detached criteria keeps its join type"() {
    given:
    def detached = new DetachedCriteria(Pet).join('owner', JoinType.LEFT)
    def context = Mock(JpaQueryContext)

    when:
    new QueryAliasRegistrar(detached, null).registerDetachedJoins(context)

    then:
    1 * context.registerAlias('owner', new HibernateAlias('owner', 'owner', JoinType.LEFT))
}

def "a dotted property name registers an inner alias for its first segment"() {
    given:
    def context = Mock(JpaQueryContext) { hasAlias('owner') >> false }

    when:
    new QueryAliasRegistrar(new DetachedCriteria(Pet), null)
            .discover([new Query.Equals('owner.name', 'x')], context)

    then:
    1 * context.registerAlias('owner', new HibernateAlias('owner', 'owner'))
}

def "an alias the context already knows is not registered again"() {
    given:
    def context = Mock(JpaQueryContext) { hasAlias('owner') >> true }

    when:
    new QueryAliasRegistrar(new DetachedCriteria(Pet), null)
            .discover([new Query.Equals('owner.name', 'x')], context)

    then:
    0 * context.registerAlias(_, _)
}

HibernateAlias is a record, so the interaction matchers compare it by value. The association-block case from this PR (DetachedAssociationCriteria with LEFT registered for its path) fits the same spec, and CreateAliasJoinSpec can then stay for the query-level behavior (one join, the right rows) instead of carrying the alias rules too.

One smaller point from the same read: the two createAlias overloads in HibernateCriteriaBuilder repeat each other (the two-argument one is the three-argument one with INNER), so the two-argument one can delegate.

Happy to send this as a patch on top of your branch, or you can take it as it is, whichever you prefer.

@borinquenkid

Copy link
Copy Markdown
Member

Thanks for the fix, @ruthst00, I appreciate it. While reviewing I saw an opportunity to refactor and improve the coverage, so I pushed one commit on top of your branch (5d5d37b).

It moves the alias registration out of JpaCriteriaQueryCreator into a package-private QueryAliasRegistrar. The duplicated block in createQuery() and populateSubquery() is now one call, and the behaviour is unchanged. QueryAliasRegistrarSpec adds 10 database-free unit specs for the join types and alias discovery. Your CreateAliasJoinSpec and the existing JpaCriteriaQueryCreatorSpec still pass.

@ruthst00

ruthst00 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

@borinquenkid, the refactoring is a great improvement! It definitely improves the cohesiveness, readability, and testability of the code. Thanks for this!

@ruthst00

Copy link
Copy Markdown
Contributor Author

@borinquenkid, @jdaugherty, are there any other changes you would like to this PR? Should it be retargeted to 9.0.x?

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

Thanks, both. Verified on this branch locally (JDK 21): CreateAliasJoinSpec, QueryAliasRegistrarSpec, ExpressionResolverSpec and JpaCriteriaQueryCreatorSpec pass, codeStyle passes, and the issue's entity select (createAlias('likes', 'l') + eq('l.id', ...) without projections) now joins the association once where 8.0.x joined it twice.

One regression from the join reuse: an alias inside a subquery now binds to the outer query's join of the same path, which changes the subquery's result (details and a regression test inline). Two smaller asks inline on the tests and the docs, plus a header nit.

The workflow runs for this PR are all waiting for approval, so nothing has run in CI yet.

@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 approving. Join-type preservation and the single-association dedupe look right, and the public signatures are unchanged. The new path lookup still produces wrong results in two cases the new tests do not cover.

JoinTracker.getJoin walks the parent tracker, so a subquery alias whose association path matches an outer join binds to that outer join. Separately, the first explicit alias records its element join under the association path, so a second alias of the same basic collection is collapsed onto that join, and a later collection operation such as sizeEq can resolve the collection path to the element join.

The existing correlated-alias test covers an inherited alias, not a new local alias that collides with an outer join. CreateAliasJoinSpec has no outer association join on the same path. QueryAliasRegistrarSpec constructs the package-private registrar directly; the regressions above need public createCriteria() / DetachedCriteria coverage.

@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 approving. The element-collection half of the earlier comment is fixed. Two aliases of a basic collection stay on different joins, and sizeEq after an element alias resolves the collection. The five affected specs passed: 64 tests, 0 failures.

The subquery half is only fixed when the inner alias is a different name from the association path. createAlias('favorite', 'favorite') inside the subquery still hits the parent-aware alias lookup before the new query-local path lookup, so the predicate binds to the outer favorite. The new exists test uses inside, so it misses that collision.

Entity-valued collections are also still recorded under the association path. likes('a') and likes('b') on the same entity collection collapse onto one join, so both predicates have to match the same element.

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

This an AI assisted review

I checked the current head (69b2726) against its merge-base on 8.0.x (0e8fd03) by running a throwaway probe spec on both. The new CreateAliasJoinSpec passes on the PR. Findings below. I agree with @jamesfredley's open point that a subquery alias named after the association path (createAlias('favorite', 'favorite')) must take precedence over the outer join, and I don't repeat it here.

Fixed by this PR (the base fails, the PR passes)

  • createAlias('likes', 'l'); eq('l.id', x); sizeEq('likes', 2) on an entity collection: the base returns ['two', 'two'] and the PR returns ['two']. The PR's size tests only cover the basic collection schools. Please add the entity-collection case too, because it takes the getOwnJoin(def.path()) branch that the basic collection skips.
  • createAlias('favorite', 'f', 1) with or { isNull('favorite'); eq('f.label', ...) }: the base drops the row that has no favorite, and the PR keeps it. The existing left-alias feature already covers this.

Two aliases of one entity collection fail on the base too

createAlias('likes', 'a'); createAlias('likes', 'b'); eq('a.id', ...); eq('b.id', ...) throws PathElementException: Could not resolve attribute 'a' of ...Team, on both the base and this PR. The cause is not in this PR: AbstractDetachedCriteria.createAlias keeps one DetachedAssociationCriteria per association path, so the second call just runs setAlias('b') and a is lost. So the regression test asked for in the last review can't pass without a change in grails-datamapping-core. I'd suggest a separate issue for it: either support independent aliases, or reject a duplicate path the way Hibernate 5 does ("duplicate association path"). Keep in mind that if datamapping ever does support it, getOwnJoin(def.path()) would put both aliases on the first join. That is the same reason the element-collection branch has to skip path registration, so the two need to be decided together.

Subquery dotted path with no alias of its own (also fails on the base)

def inner = new DetachedCriteria(Team).build { eq('favorite.label', 'second') }
Team.withCriteria {
    createAlias('favorite', 'outside')
    eq('outside.label', 'first')
    exists(inner)
}

This should return team A and returns [] on both the base and the PR, so it is not a regression. But the cause looks like the one in the open collision comment. createAlias also calls detachedCriteria.join('favorite', ...), so the outer context defines an alias named favorite. Inside the subquery, discover() then skips the implicit favorite alias because hasAlias sees the parent's, and the predicate resolves against the outer query. On this branch the outer join is now also recorded under the path key favorite, so resolveFromAlias → joinTracker.getJoin('favorite') finds it straight away. The same rule (a path used inside a subquery resolves from the subquery's root unless an explicit outer alias is referenced) should fix both. The new docs say aliases declared in a subquery join from its own root, and readers may assume that holds for plain dotted paths as well. Please cover this case or file it as a follow-up.

Minor

  • QueryAliasRegistrarSpec tests the package-private QueryAliasRegistrar with a mocked JpaQueryContext, and JoinTrackerSpec calls getOwnJoin directly. The project guideline is to test through the public criteria API. CreateAliasJoinSpec already does that well, so the mock-interaction specs mostly pin the refactor's shape rather than its behaviour.
  • JoinTracker keeps aliases and association paths in the same joinsByPath map. An alias spelled like another property (createAlias('favorite', 'likes')) can therefore shadow a later likes { ... } association criterion. That isn't new, but this PR adds more path keys to the map. Separate maps (or a prefix) would make the precedence the reviewers are asking for easier to express.

@ruthst00

ruthst00 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@sbglasius, I made your recommended changes in 7bc7691, ede40fe

@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 approving. The subquery case where the inner alias is a different name from the association path is covered. Two remaining alias collisions still return no rows for queries that match on the base revision.

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

Review of #16573 at ede40fec69 (base 8.0.x). It is six commits on 0e8fd03e56c, 191 commits behind the current 8.0.x tip 75a355a3aeb, and git merge-tree against the tip is clean.

What I ran and checked:

  • Tests at the head: CreateAliasJoinSpec, 25 tests, all green. The full :grails-data-hibernate7-core:test suite, run after cleanTest without the build cache: 3670 tests, 0 failures, 15 skipped.
  • Style: Checkstyle and CodeNarc on the module's main sources are clean.
  • Probe spec, not committed, run at the head and at the merge-base 0e8fd03e56c: its own Team { Like favorite; hasMany likes: Like }, Like { String label } and Student { hasMany schools: String }, with the SQL captured through a statement inspector. The results are in the tables below.
  • CI: no workflow has run on this PR yet; the runs are still waiting for approval.

The issue's own case is fixed: one alias now makes one join, and the join keeps its type. On 8.0.x, list(max: 10) { createAlias('likes', 'l'); eq('l.label', 'first') }.totalCount counts 3 for 2 matching teams because of the unused second join; at the head it counts 2. An inner alias in a subquery now joins from the subquery's own root, whatever its name.

But jamesfredley's two open comments from this morning are regressions against 8.0.x, not gaps in the new feature: both queries return the right rows on the merge-base and the wrong rows at the head. I'd like 1 fixed before merge, and 2 fixed or the docs narrowed. 3 and 4 are smaller.

1. The two open alias/path collisions break queries that work on 8.0.x

Query 8.0.x head
createAlias('likes', 'likes'); createAlias('likes', 'other'); eq('likes.label', 'first'); eq('other.label', 'second') [both] []
createAlias('favorite', 'f'); createAlias('likes', 'favorite'); eq('favorite.label', 'y'), with property('f.label') in the projections [[x, T1]] [[y, T2]]
the same with order('f.label') instead of the projection [T1] [T2]
the same with eq('f.label', 'x') as a restriction, no projection or order [T1] [T1]

In the first query the head joins likes once and puts both restrictions on that join (l1_1.label=? and l1_1.label=?). In the second, favorite.label lands on the favorite join (f1_0.label=?) and the likes join is left unrestricted. The second only goes wrong when f is resolved before the association criteria, which is what a projection or an order does: JpaCriteriaQueryCreator.createQuery adapts projections and orders before assignCriteria.

Both come from the same two places:

  • JoinTracker.joinsByPath (JoinTracker.java:29) holds alias names and association paths in one map, and ExpressionResolver.resolveFromAlias now also registers an alias's join under its association path (ExpressionResolver.java:137-139). The lookup by alias name at line 113 then reads the path entry favorite as the alias favorite.
  • Whether an alias was declared is guessed from its name, explicitAlias = !alias.equals(def.path()) (ExpressionResolver.java:129), so createAlias('likes', 'likes') counts as implicit and never claims its join. QueryAliasRegistrar.discover uses the same guess for inheritedPath (QueryAliasRegistrar.java:127).

Rather than another special case, I'd separate the two namespaces, as sbglasius suggested:

  • Keep the joins made for an association path in a map of their own, used by PredicateGenerator.handleAssociationCriteria and by step 3 of resolveFromAlias, apart from the joins of named aliases.
  • Record whether an alias was declared. QueryAliasRegistrar knows: aliases from createAlias and from a DetachedAssociationCriteria are declared, and the ones from registerDetachedJoins and dotted-path discovery are implicit. A flag on HibernateAlias, or a set of declared names in the context, would do. Then the identity set explicitlyAliasedJoins and the name comparison can go.

Please add both queries to CreateAliasJoinSpec, the second with the alias in a projection or an order.

2. Two aliases of one entity collection: totalCount and count with projections still throw

The docs now say that two aliases of one entity collection in createCriteria() or withCriteria make independent joins (createCriteria.adoc:84), and the same page shows list(max: ...) with totalCount. With createAlias('likes', 'a'); createAlias('likes', 'b'); eq('a.label', 'first'); eq('b.label', 'second'):

Call 8.0.x head
list(max: 10) { } PathElementException [both]
count { } PathElementException 1
list(max: 10) { }.totalCount PathElementException PathElementException: Could not resolve attribute 'a'
count { ...; projections { property('name') } } PathElementException PathElementException: Could not resolve attribute 'a'

AbstractDetachedCriteria.createAlias keeps one DetachedAssociationCriteria per path, and the second call only renames it (AbstractDetachedCriteria.groovy:140-147). So a exists only in HibernateQuery.aliases, and two code paths lose that list:

  • HibernateQuery.clone() (HibernateQuery.java:866-882) doesn't copy it, and HibernatePagedResultList.getTotalCount() counts on a clone (HibernatePagedResultList.java:96).
  • countResults() with projections builds its JpaCriteriaQueryCreator without the query (HibernateQuery.java:545).

This isn't a regression, since 8.0.x can't run the query at all, but totalCount usually comes with a paged criteria list. The same gap already breaks a basic-collection alias on both revisions: Student.createCriteria().list(max: 10) { createAlias('schools', 's'); eq('s', 'MIT') }.totalCount throws Cannot use comparison criteria on non-existent property [s].

Copying aliases in clone() and passing this in the projection branch of countResults() would fix both. Alternatively, createAlias could add the HibernateAlias to the detached criteria. QueryAliasRegistrar.explicitAliases() already reads it from there, DetachedCriteria.clone() copies the criteria, and PredicateGenerator treats it as metadata.

3. The first of two entity aliases takes the join type of the last createAlias

createAlias('likes', 'a'); createAlias('likes', 'b', 1); isNull('a.label') returns the team without likes, from a single left join:

select pt1_0.name from probe_team pt1_0
left join probe_team_probe_like l1_0 on pt1_0.id=l1_0.probe_team_likes_id
left join probe_like l1_1 on l1_1.id=l1_0.probe_like_id
where 1=1 and l1_1.label is null

a is an inner join, so that team should be excluded. join(path, type) overwrites joinTypes[path] (AbstractDetachedCriteria.groovy:172). The join of the association criteria takes that type, and the first explicit alias reuses it without comparing types (ExpressionResolver.java:128-134). Basic collections keep each alias's own type, and CreateAliasJoinSpec tests that, but entity collections don't. Reusing the path join only when its type equals def.joinType() would fix it. 8.0.x throws on this query, so it isn't a regression.

4. The docs on dotted paths in subqueries only hold for the first property of a comparison

createCriteria.adoc:82 says that a plain dotted path in a detached subquery resolves from the subquery's own root. That holds for eq('favorite.label', ...): this PR fixes it (8.0.x: [], head: [A]). It doesn't hold for the second property of a property comparison:

def ownNameIsOwnFavorite = new DetachedCriteria(Team).build {
    eqProperty('name', 'favorite.label')
}
Team.withCriteria {
    createAlias('favorite', 'outside')
    eq('outside.label', 'first')
    exists(ownNameIsOwnFavorite)
}

Both revisions return [], because the subquery correlates on the outer row (where f2_0.id=pt1_0.favorite_id and pt2_0.name=f2_0.label). QueryAliasRegistrar.discover reads only getProperty() (QueryAliasRegistrar.java:121-131), never PropertyComparisonCriterion.getOtherProperty().

Discovering the other property as well would match the docs. The existing eqProperty('label', 'outside.label') test would still correlate, since outside isn't a path alias. Otherwise, please narrow the sentence. An association block inside the subquery (favorite { ... }) also still binds to the outer join, as jdaugherty noted; that one could go in a follow-up issue.

5. Smaller points

  • Duplicate overload: the two-argument createAlias can delegate to the three-argument one with 0 (HibernateCriteriaBuilder.java:232-241). borinquenkid raised this in the first review.
  • Doc placement: the new section sits between Examples and Description on the general createCriteria reference page, and most of it describes Hibernate 7 behaviour. The GORM for Hibernate 7 guide (grails-data-hibernate7/docs/src/docs/asciidoc/querying/criteria.adoc) doesn't cover createAlias yet. The subquery and collection-alias rules would fit better there, and the reference page could keep the join-type codes and the left-join example.
  • Commits: please squash on merge; two of the six commits have the same message.

Verified as correct

  • Single alias: at the head, createAlias('likes', 'l') used in a restriction, a projection and an order makes one join (SQL checked). The left and right join types reach the query.
  • Subquery aliases: an inner alias named inside, favorite or outside joins from the subquery's root. An outer alias that the subquery only references by name (eqProperty('label', 'outside.label')) still correlates.
  • AliasRegistry.getRealized: the new !isOwnDefined check only shadows the parent in a context that declares the alias. The nested contexts of association blocks declare none, so their lookups are unchanged.
  • Docs: the join-type codes match convertFromInt (1 left, 2 right, anything else inner) and Hibernate 5's JoinType.parse.
  • Header and @since 8.0.1 on QueryAliasRegistrar match projectVersion=8.0.1-SNAPSHOT, and the new files carry no @author tag.

/**
* Whether this query declares the alias, independently of any enclosing query.
*/
public boolean isOwnDefined(String alias) {

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 more small point I missed in the review: this can be package-private. All its callers (ExpressionResolver, QueryAliasRegistrar) and AliasRegistrySpec are in org.grails.orm.hibernate.query, and JpaQueryContext only exposes the registry through the protected getAliasRegistry(). QueryAliasRegistrar is already package-private, and this keeps the other new internals out of the public surface too. If finding 1 moves to a declared flag on HibernateAlias, the call in QueryAliasRegistrar may go away as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in cdd00b8

* Returns the join registered by this query, ignoring enclosing queries because
* an association path is relative to the root of the query it appears in.
*/
public From<?, ?> getOwnJoin(String path) {

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.

Same here: getOwnJoin can be package-private. Its only caller is ExpressionResolver in the same package, and JpaQueryContext only exposes the tracker through the protected getJoinTracker().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in cdd00b8

@ruthst00
ruthst00 force-pushed the fix/16562-h7-create-alias branch from ede40fe to 644adf8 Compare October 22, 2026 17:08
@ruthst00

ruthst00 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@matrei, to keep the latest commit relatively simple, I resolved your first two sections:

  1. The two open alias/path collisions break queries that work on 8.0.x
  2. Two aliases of one entity collection: totalCount and count with projections still throw

...and left your other recommended changes for another commit that I will work on soon.

All commits have been squashed into 644adf8

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

The two earlier alias collisions are fixed. An explicit alias is tracked by declaration, not by whether its name equals the path, and a later alias of the path name no longer reuses the favorite join. Those two threads are resolved. Not approving. An explicit join that nothing references can still be dropped.

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

Re-checked at 644adf8. :grails-data-hibernate7-core:test passes locally (3693 tests, 0 failures, 15 skipped). Three of my four threads from the first round are fixed and resolved. The subquery one is fixed as well, with one test still to add (reply on that thread).

I compared this head with the merge-base 0e8fd03 using a throwaway probe spec. One regression, inline: a subquery over another entity can no longer correlate through the outer query's association path.

These now return the right rows here, and fail or return wrong rows on the merge-base, but no test covers them yet:

  • createAlias('likes', 'a'); createAlias('likes', 'b', 1); isNull('a.label') returns [], with a kept as an inner join (merge-base: PathElementException). This is matrei's item 3, so it only needs a regression test now.
  • new DetachedCriteria(Team).build { createAlias('likes', 'l'); eq('l.label', 'first') } counts 2 with count() and with list(max: 1).totalCount (merge-base: 3, from the second join).
  • tag { eq('name', 'a') }; likes { eq('tag.name', 'b') }, where both Team and Like have a tag, returns the matching team (merge-base: [], because the nested tag.name reused the outer tag join).

I also reproduced jamesfredley's open thread: createAlias('favorite', 'a', 1); createAlias('favorite', 'b', 0) with only a referenced keeps the team that has no favorite.

@ruthst00

Copy link
Copy Markdown
Contributor Author

@matrei, I implemented your remaining feedback in cdd00b8. Please review. Thanks

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

Re-checked at 64ac919. :grails-data-hibernate7-core:test passes locally (3723 tests, 0 failures, 15 skipped), and my probe spec against the merge-base 0e8fd03 confirms:

  • The correlated subquery over another entity returns [B] again, with the outer path and with createAlias('favorite', 'f'), and both variants are in CreateAliasJoinSpec. Resolved.
  • The association block inside a subquery has its test. Resolved.
  • createAlias('favorite', 'a', 1); createAlias('favorite', 'b', 0) with only a referenced now excludes the team without a favorite.

One new regression, inline: now that every explicit alias is materialized, an unused basic-collection alias joins, which changes rows and counts that 8.0.x returns. Limiting the materialization to entity aliases fixes that and keeps the favorite cases.

Two of the tests asked for last round are still missing:

  • new DetachedCriteria(Team).build { createAlias('likes', 'l'); eq('l.label', 'first') } with count() and list(max: 1).totalCount (2 here, 3 on the merge-base).
  • tag { eq('name', 'a') }; likes { eq('tag.name', 'b') } with tag on both Team and Like (the matching team here, [] on the merge-base).

@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 review of #16573 at 747874a287 (base 8.0.x). The branch now merges 8.0.x at 9c073cdc711, which is 53 commits behind the current tip 956b3e719d8.

What I ran and checked:

  • Build at the head: :grails-data-hibernate7-core:compileGroovy fails. See 1.
  • Local merge with the current 8.0.x tip, not pushed, with the fixes from 1 and 2: the full :grails-data-hibernate7-core:test suite, run after cleanTest without the build cache: 4281 tests, 0 failures, 21 skipped. Checkstyle and CodeNarc on the module's main sources are clean.
  • The probe spec from my first review, not committed, with jdaugherty's basic-collection table and a few association-block queries added. I ran it on that merge and on the 8.0.x tip.
  • CI: the workflows for this head are still waiting for approval, so nothing has run.

All five points from my first review are fixed, and the probe confirms each one (table below). Association-path joins and named aliases are now kept apart, and each alias records whether it was declared, as sbglasius and I suggested. What blocks the merge now is the merge commit itself.

1. The head doesn't compile

JpaCriteriaQueryCreator.java:299: error: cannot find symbol
            } else if (criterion instanceof DetachedAssociationCriteria<?> dac) {

The merge 747874a287 resolved the conflict with #16731 (ebc4b2a4e3b, which adds isCountOnly()) by taking the whole 8.0.x side of the hunk. That side still holds the old discoverAliases and registerDetachedJoins, which this PR moved into QueryAliasRegistrar, while the DetachedAssociationCriteria import stays removed. When I redo the merge with git, the result differs only in the conflict markers, so nothing else was lost. Delete the two private methods (JpaCriteriaQueryCreator.java:291-323) and keep isCountOnly(); nothing calls either method.

2. Conflict with the current 8.0.x

#16758 (c92ba20fcc4, merged after your last push) adds Join and JoinType imports to PredicateGenerator, in the block where this PR removes JoinType. Keep Join, which PredicateGenerator.java:551 uses, and drop JoinType, which nothing uses after this PR. With that resolution, #16758's CollectionCriterionAssociationBlockSpec passes as part of the suite above. Since the PR will be squashed anyway, a rebase onto 8.0.x would also avoid another merge commit.

The first review's findings

Probe results on the 8.0.x tip and on this PR merged into it:

# Query 8.0.x this PR
1 createAlias('likes', 'likes'); createAlias('likes', 'other'), both restricted [both] [both]
1 createAlias('favorite', 'f'); createAlias('likes', 'favorite'); eq('favorite.label', 'y') with f in a projection, an order, a restriction [[x, T1]], [T1], [T1] the same
2 two aliases of likes: list(max: 10), .totalCount, count {}, count {} with a projection PathElementException [both], 1, 1, 1
2 createAlias('schools', 's'); eq('s', 'MIT') with .totalCount Cannot use comparison criteria on non-existent property [s] 1
3 createAlias('likes', 'a'); createAlias('likes', 'b', 1); isNull('a.label') PathElementException []
4 eqProperty('name', 'favorite.label') in an exists subquery [] [A]

Point 5 is done too: the two-argument createAlias delegates, the Hibernate 7 rules are in the H7 guide with a link from the reference page, and isOwnDefined and getOwnJoin are package-private.

3. Smaller points

  • Visibility: the new AliasRegistry.getAssociationAlias (AliasRegistry.java:79), ExpressionResolver.resolveAssociation (ExpressionResolver.java:137) and JpaQueryContext.resolveAssociation (JpaQueryContext.java:126) are only called from org.grails.orm.hibernate.query and its specs. Like isOwnDefined and getOwnJoin, they can be package-private.
  • Two aliases of one collection in a DetachedCriteria: new DetachedCriteria(Team).build { createAlias('likes', 'a'); createAlias('likes', 'b'); eq('a.label', 'first'); eq('b.label', 'second') } still throws Cannot use comparison criteria on non-existent property [a.label] (8.0.x: PathElementException). A DetachedCriteria keeps one association criteria per path, and the second createAlias renames it. The guide already limits independent joins to createCriteria() and withCriteria. A sentence saying that a DetachedCriteria keeps only the last alias of a path would make that limit explicit. This could also be a follow-up.
  • Commits: 5eff154bbb and 735e492162 have the same message again. Please squash on merge.

Verified as correct

  • Separate namespaces: JoinTracker now holds only association-path joins and AliasRegistry only named aliases. HibernateAlias.explicit replaces the name comparison, and explicitlyAliasedJoins is gone. QueryAliasRegistrar marks aliases from registerDetachedJoins and dotted paths as implicit, and aliases from createAlias and DetachedAssociationCriteria as declared.
  • The issue's own case: list(max: 10) { createAlias('likes', 'l'); eq('l.label', 'first') }.totalCount is 2 (8.0.x: 3).
  • Unused basic-collection aliases: jdaugherty's four queries return the 8.0.x rows and counts ([grace, hank], 2, [grace, hank, none], [grace, hank, none]), and BasicCollectionInQuerySpec has its original expectation back.
  • An association block next to an alias: in createAlias('likes', 'l', 1); or { isNull('l.label'); likes { eq('label', 'first') } } the block now uses the alias's left join and returns [both, first only, none]. 8.0.x joins likes twice and returns [both, both, first only].
  • Unreferenced entity aliases: the one 8.0.x result I found that changes is createAlias('likes', 'a', 1); createAlias('likes', 'b'); likes { eq('label', 'first') }. The unreferenced b is now its own inner join, so a team with two likes comes back twice; 8.0.x makes both aliases one join. The guide describes this for an explicit alias that nothing references, so I don't think it needs a change.
  • Doc links: hibernate7GuideFromRef is defined in grails-doc/build.gradle:640, and both anchors exist: [[criteria]] in the H7 guide's index.adoc:172 and [[criteriaAssociationAliases]] at criteria.adoc:152.
  • Tests: the queries from my first review's tables and from jdaugherty's two rounds are in CreateAliasJoinSpec, most with assertions on the number of joins in the SQL.

@ruthst00
ruthst00 force-pushed the fix/16562-h7-create-alias branch from 747874a to 6d0f7bc Compare October 27, 2026 07:34

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

This an AI assisted review

Re-checked at 6d0f7bc808. The branch is rebased onto the current 8.0.x tip (87fdc9f3f8) with no merge commit, and git merge-tree is clean. Matrei's compile error and the PredicateGenerator conflict are gone.

What I ran:

  • :grails-data-hibernate7-core:cleanTest test, without the build cache: 4377 tests, 0 failures, 21 skipped.
  • :grails-data-hibernate7-core:codeStyle: Checkstyle fails (see 1). CodeNarc on main sources is clean.
  • A throwaway probe spec, run on this head and on the 8.0.x tip.

Both points from my earlier review are covered now. an entity collection alias preserves size restrictions without multiplying rows covers the entity-collection sizeEq. The plain dotted path in a subquery resolves from the subquery's root, and the registrar mock spec is gone.

1. Checkstyle fails on the main sources

JpaCriteriaQueryCreator.java:292:5: 'METHOD_DEF' has more than 1 empty lines before. [EmptyLineSeparator]
PredicateGenerator.java:38:8: Unused import - jakarta.persistence.criteria.JoinType. [UnusedImports]
  • The first is left over from deleting discoverAliases and registerDetachedJoins: two blank lines remain before assignCriteria.
  • The second is the import matrei asked you to drop when resolving the conflict with #16758. Keep Join, but drop JoinType, since nothing uses it after this PR.

The PR description says Checkstyle passed, so please re-run ./gradlew :grails-data-hibernate7-core:codeStyle before the next push. The same hunk also re-indents the isCountOnly() stream continuation lines. That is unrelated to this change, so please revert it.

2. Visibility (matrei's point 3, still open)

AliasRegistry.getAssociationAlias, ExpressionResolver.resolveAssociation and JpaQueryContext.resolveAssociation are still public. Their only callers are in org.grails.orm.hibernate.query and its specs, the same as isOwnDefined and getOwnJoin, which are now package-private.

3. Subquery correlation through a plain path depends on the order of restrictions (not a regression)

A subquery over Like that correlates with eqProperty('favorite.label', 'label') only works when the outer query has already joined favorite by the time the subquery is built:

Outer query 8.0.x this head
isNotNull('favorite.label'); exists(sub) [B] [B]
exists(sub); isNotNull('favorite.label') PathElementException: Could not resolve attribute 'favorite' of 'Like' the same
createAlias('favorite', 'f'); exists(sub); isNotNull('f.label') [B] [B]

The behaviour is the same as on 8.0.x, so this doesn't block. But the new guide text says the path "can instead reference an existing enclosing query join" and that it "works whether the outer join comes from a dotted path restriction or createAlias". A reader won't see from that that a dotted-path restriction has to come before the exists. One sentence would cover it: a dotted-path join must be declared first, or use createAlias on the outer query. Alternatively, file a follow-up to resolve the enclosing path lazily.

4. Commits

5718f689b5 and 6d0f7bc808 have the same message but different content. That's fine as long as the PR is squashed on merge, as already noted.

Verified, no change needed

  • An unused entity alias (createAlias('favorite', 'f') alone) excludes the team without a favorite in both withCriteria and DetachedCriteria. rowCount() with an unused likes alias gives the same count as on 8.0.x. The eager materialization in QueryAliasRegistrar.createContext doesn't change those existing results.
  • HibernateQuery.clone() copying aliases, and the projected count passing the owning query, look right. The pagination and count specs cover them.

@ruthst00
ruthst00 force-pushed the fix/16562-h7-create-alias branch from 6d0f7bc to 9003f57 Compare October 27, 2026 08:45
@ruthst00

Copy link
Copy Markdown
Contributor Author

@sbglasius, @matrei, thanks for your feedback. As you suggested I:

  1. Rebased the PR branch with 8.0.x
  2. Fixed checkstyle errors
  3. Changed public methods to private
  4. Updated criteria.adoc
  5. Squashed commits and force-pushed

Please let me know if I missed anything :o)

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Third review of #16573 at 9003f5796d (base 8.0.x). It is one commit on the current tip 87fdc9f3f84, and it merges cleanly.

@ruthst00, thanks for the rebase and the squash. To answer your question: two things in the last push need another look, the visibility change (1) and the guide paragraph (2).

At 6d0f7bc808 I found the same things sbglasius did: the two Checkstyle errors, the three public methods and the isCountOnly() indentation. So this only covers what the squash changed.

What I ran and checked:

  • Build at the head: :grails-data-hibernate7-core:compileGroovy fails. See 1.
  • The head with the fix from 1 applied locally: it compiles, checkstyleMain passes, and CreateAliasJoinSpec, BasicCollectionInQuerySpec and the org.grails.orm.hibernate.query specs pass (660 tests, 0 failures). At 6d0f7bc808, which has the same logic, the full :grails-data-hibernate7-core:test suite passed (4356 tests, 0 failures).
  • CI: the workflows are still waiting for approval, so nothing has run.

1. The head doesn't compile

ExpressionResolver.java:120: error: getAssociationAlias(String) has private access in AliasRegistry
ExpressionResolver.java:140: error: getAssociationAlias(String) has private access in AliasRegistry
JpaQueryContext.java:129: error: resolveAssociation(String,JoinType) has private access in ExpressionResolver
PredicateGenerator.java:308: error: resolveAssociation(String) has private access in JpaQueryContext
PredicateGenerator.java:323: error: resolveAssociation(String) has private access in JpaQueryContext

The ask was package-private, not private. Each of the three methods is called from another class in the same package. Remove the access modifier, as you did for isOwnDefined and getOwnJoin:

HibernateAlias getAssociationAlias(String path) {          // AliasRegistry.java:79
From<?, ?> resolveAssociation(String path, JoinType joinType) {  // ExpressionResolver.java:137
From<?, ?> resolveAssociation(String path) {               // JpaQueryContext.java:126

Please run ./gradlew :grails-data-hibernate7-core:codeStyle :grails-data-hibernate7-core:test before the next push.

2. The subquery paragraph in the guide was replaced, not extended

The paragraph in "Aliases in Subqueries" (criteria.adoc:185) explained how a plain dotted path in a subquery resolves: from the subquery's own root, for either operand of a property comparison, through an enclosing join when the subquery's entity lacks the association, and how to correlate explicitly with an outer alias. It is now only:

A dotted-path join must be declared first, or use createAlias on the outer query.

Without the paragraph, that sentence has nothing to refer to. sbglasius suggested adding a sentence. Please restore the paragraph and add it after "This works whether the outer join comes from a dotted path restriction or createAlias('favorite', 'f')." For example: "A dotted-path restriction in the outer query must come before the exists; otherwise, use createAlias on the outer query."

3. Smaller points

  • isCountOnly(): the continuation lines from #16731 are still re-indented (JpaCriteriaQueryCreator.java:287-288). +1 to sbglasius's ask to revert that.
  • Commit message: the squashed message is the log of every review round, and the "Addressed @jdaugherty's feedback" section appears twice. A short message that describes the fix (#16562: one join per alias, each alias keeps its join type, aliases scoped to their own query) would read better in the history.

@ruthst00
ruthst00 force-pushed the fix/16562-h7-create-alias branch from a953d79 to ba30bb7 Compare October 27, 2026 09:51
@ruthst00

Copy link
Copy Markdown
Contributor Author

@matrei, thank you for your patience. Here are the latest changes:

  • Removed access modifier for 3 methods
  • Restored original "Alias in Subqueries" paragraph in criteria.adoc and appended with instructions for using dotted paths.
  • Un-indented isCountOnly() stream code
  • Ran ./gradlew :grails-data-hibernate7-core:codeStyle :grails-data-hibernate7-core:test before the next push.
  • Squashed and simplified commit message

@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 approving. One join per alias and the requested join type stay. A createAlias inside an association block is still joined from the outer entity, and the next query on the same builder keeps that join.

@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 nested createAlias is joined from the association that declared it, and the next list on the same builder does not keep that join. Not approving. A subquery that correlates through an association join the outer query did not name as an alias drops that comparison, so rows that do not share the association match. This is a bugfix, so 8.0.x can keep it.

@ruthst00

ruthst00 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@matrei, thanks again. I made your final doc changes and squashed all commits.

@matrei

matrei commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@jdaugherty, your review at d3a1f3af74 is the last one requesting changes. I went through your four open threads at the squashed head 48c7216663, and all four are addressed:

  • PredicateGenerator.java:312, an alias inside or { } made the junction true: handleAssociationCriteria now returns null when the association criteria has no criteria of its own, after createContext, as you suggested. a left alias inside a disjunction does not override its restrictions uses your five-team example and checks the list (B, C, D, E), count() and totalCount (4).
  • createCriteria.adoc:103: the sentence starts with "In Hibernate 7," and is followed by "Hibernate 5 resolves the alias path from the domain class being queried."
  • JpaCriteriaQueryCreator.java:287: isCountOnly() is identical to 8.0.x.
  • BasicCollectionInQuerySpec.groovy:156: you verified this one in your last review, but the thread is still open.

The code at 48c7216663 is the same as at 7f61831387; only the docs changed. At 7f61831387 merged with the current 8.0.x tip, the full :grails-data-hibernate7-core:test suite passed (4450 tests, 0 failures). Could you re-review and resolve the threads when you have time?

You also mentioned two follow-up issues. I couldn't find them, and both still reproduce at 48c7216663 and on the 8.0.x tip:

  • projections { property('zz.name') } returns the entities, and order('zz.name') fails with AssertionError: null.
  • On one createCriteria() builder, list { eq('name', 'both') } followed by count { } counts 1, while a new builder counts all 4 teams.

Are you still opening them? #16815 covers unresolved paths in property comparisons, but not these two.

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

This an AI assisted review

Re-checked at 48c7216663, one commit on 87fdc9f3f8 that merges cleanly with the current 8.0.x tip.

The code is the same as 7f61831387, which jamesfredley and matrei approved. The squash changed only the two doc points from matrei's fourth review: exists is in backticks, the Hibernate 5 sentence on the reference page now comes before the list { ... } sentence, and the paragraph about embedded paths in association blocks is gone. Every CI job on this head passes, including the Hibernate 7 core and functional suites.

Both points from my earlier reviews are still covered. The open asks from jdaugherty's last review look done to me:

  • createAlias(..., 1) inside or { } no longer makes the disjunction always true. handleAssociationCriteria returns null for an empty association criteria after its context is built, and a left alias inside a disjunction does not override its restrictions covers it, with pagination.
  • The reference page now states the Hibernate 5 behavior separately from the Hibernate 7 rule for block-local aliases.
  • isCountOnly() is no longer touched by the diff.

Non-blocking:

  • The commit message still says "liases". Please fix it to "aliases" when the commit is squashed on merge.
  • CreateAliasJoinSpec:513-514 asserts rows.totalCount == 2 twice. If that checks that a second read gives the same count, a short comment would make it clear. If not, drop one.
  • Follow-ups that were agreed to stay out of this PR: the three-argument createAlias inside a junction resolving against the outer entity (matrei), and the two pre-existing issues jdaugherty offered to open (a projection or order on an alias that doesn't exist, and reusing a builder for count { } after list { }). It would help to link them here once they are filed.

Approving.

…keeps its join type, and aliases are scoped to their own query.
@ruthst00
ruthst00 force-pushed the fix/16562-h7-create-alias branch from de55345 to 7e0159f Compare November 4, 2026 15:57
@ruthst00

ruthst00 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@sbglasius, thank you for your review. I added a comment to CreateAliasJoinSpec:513-514 which asserts rows.totalCount == 2 twice. Then I squashed all commits and fixed the commit message to say "aliases".

@borinquenkid borinquenkid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving at 7e0159f.

I read the production diff end to end. The split is the one sbglasius, matrei and I asked for: JoinTracker holds only association-path joins, AliasRegistry only named aliases, and HibernateAlias.explicit replaces the name-equals-path guess. getRealized stops at an own-defined alias instead of walking the parent, which is what keeps a subquery alias off the outer join. getPath swallows a missing attribute, so the implicit branch in resolveFromAlias can safely treat "not on my root" as "enclosing join", and getPredicates filters nulls, so the empty-block return null in handleAssociationCriteria is safe. jdaugherty's four open threads are addressed at this head, as matrei walked through; the "changes requested" state is the stale review from d3a1f3a, not an open objection. The last push changed only test comments and the commit message.

Two things to settle around the merge, neither against this PR:

  1. #16559 overlaps this PR now. When jdaugherty checked, the files didn't overlap; at this head both PRs rewrite handleAssociationCriteria and touch AliasRegistry, ExpressionResolver, JoinTracker, JpaQueryContext and their specs. More than textual: this PR already honours nested block join types (QueryAliasRegistrar.createContext on the block registers getJoinTypes() as implicit aliases, and resolveAssociation reuses only this context's joins), so owner(1) { face(1) { ... } } renders two left joins here too. I'd merge this one first and ask #16559 to rebase and drop what it now duplicates. I'll note that on #16559.

  2. HibernateQuery.aliases is now dead. createAlias no longer calls addAlias and nothing else does, so the addAll in clone() and the getAliases() read in QueryAliasRegistrar.explicitAliases() carry nothing. Not wrong at runtime, so I opened #16860 for the cleanup rather than hold this PR.

Two non-blocking notes:

  • ExpressionResolver.resolveAssociation ignores the joinType it is passed whenever an explicit alias exists for the path; the alias's type wins. That is the documented behaviour and matrei verified it, but a one-line comment there would save the next reader a trip through the resolver.
  • jamesfredley's order('owner') case on #16559 (a projection alias with the same name as a join) is about #16559's resolver ordering, but whichever PR lands second should be re-probed against it, since both change the lookup order.

Thanks @ruthst00 for the patience through five rounds, and to everyone who ran the probe specs.

@borinquenkid borinquenkid added this to the grails:8.0.1 milestone Nov 4, 2026
@borinquenkid

Copy link
Copy Markdown
Member

@jdaugherty quick one, I know you're swamped. Your changes-requested review is from d3a1f3a and is the only thing left in the merge box: matrei walked your four open threads at the squashed head and confirmed each is addressed, and there are now four approvals (jamesfredley, matrei, sbglasius and me). I plan to merge once CI on 7e0159f is green. If a re-review isn't in the cards this week, dismissing the old review is enough, and I'll take it from there. If you'd rather I hold, say so and I will.

@testlens-app

testlens-app Bot commented Nov 4, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 7e0159f
▶️ Tests: 93155 executed
⚪️ Checks: 96/96 completed


Learn more about TestLens at testlens.app/docs.

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

Re-checked at 7e0159f, one commit on 87fdc9f. git merge-tree against the current 8.0.x tip (9b7e9ff) is clean, and nothing merged to 8.0.x since the branch point touches a file in this PR. Every CI job on this head passes.

My three asks from the last round are done:

  • An alias created inside or { } no longer makes the junction match every row. handleAssociationCriteria returns null for an association criteria that has no criteria of its own, after its context is created, and getPredicates drops it. a left alias inside a disjunction does not override its restrictions covers the five-team example with the list, count() and totalCount.
  • The reference page states the block-alias rule for Hibernate 7 and says how Hibernate 5 resolves the path.
  • isCountOnly() is identical to 8.0.x.

The one production change since then that I had not asked for is also right: QueryAliasRegistrar now takes the entity of an association block from the association. getPersistentEntity() on the block's criteria looks the entity up by class and throws Class [...] is not a domain class for a plain embedded component, and for an entity association both give the same entity. EmbeddedCriteriaAliasSpec covers it.

This head differs from 7f61831, which jamesfredley and matrei approved, only in two documentation lines and one test comment.

Approving. My four threads are resolved.

Follow-ups, none of them for this PR: I will open the two pre-existing issues from my last review (a projection or order on an alias that does not exist, and a builder reused for count { } after list { }) and link them here. #16842, #16851 and #16860 track the others, and #16559 needs a rebase once this is merged, since both now change handleAssociationCriteria.

Thanks @ruthst00 for sticking with this through every round.

@jdaugherty

Copy link
Copy Markdown
Contributor

The two follow-ups from my review are filed, both reproduced on 8.0.x at 24c6e5a, after this merge:

jdaugherty added a commit that referenced this pull request Nov 4, 2026
…ll collected

The merge of 8.0.x took the removal of the import from #16573, which no longer builds a list in this class
there. On this branch assignOrderBy still collects the orders, those its handlers build among them, in an
ArrayList. The two changes merged without a conflict, and the Hibernate 7 core did not compile.
gustavoharff added a commit to gustavoharff/grails-core that referenced this pull request Nov 4, 2026
…queries

Since apache#16573, an association block nested in another keeps the join type it
asks for, and an association block reuses only the joins of its own context.
These specs cover that behaviour:

- HibernateCriteriaBuilderNestedJoinTypeSpec, end to end through the criteria
  DSL, asserting the rows and the generated joins: nested left joins, a nested
  block without a join type, blocks of the same name at two levels, a detached
  criteria, subqueries, and an order on a projection alias with the name of an
  association block.
- PredicateGeneratorSpec: the joins built for association blocks.
- ExpressionResolverSpec: a path of a subquery taken from its own root when the
  outer query joined the same name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jdaugherty added a commit that referenced this pull request Nov 4, 2026
8.0.x now carries #16573, which reworked the same classes this branch changed (AliasRegistry, ExpressionResolver,
HibernateAlias, JpaCriteriaQueryCreator, JpaQueryContext and PredicateGenerator) and moved alias discovery into
QueryAliasRegistrar. The conflicts are resolved by taking the 8.0.x version of those classes and of
AliasRegistrySpec and JpaQueryContextSpec, whose additions on this branch pinned the isSubquery flag that 8.0.x
does not have.

SubqueryAssociationCorrelationSpec is kept. Against 8.0.x alone, 11 of its 12 features pass: #16573 already scopes
a subquery's association paths to its own root, keeps sibling association blocks on independent joins and keeps a
comparison through an inherited join. The remaining feature, an alias on a nested path such as
createAlias('owner.address', 'a'), is fixed in the next commit.
jdaugherty added a commit that referenced this pull request Nov 4, 2026
…time

createAlias('owner.address', 'a') passed the whole path to a single JPA join, which takes one attribute, so the
query failed with "Could not resolve attribute 'owner.address'". GORM validates such a path as a chain of
associations from the queried entity, so ExpressionResolver now joins it one association at a time.

The first association shares the join the query already has for it (its first alias, an association block or a
dotted property path) and keeps the join type the query gives that association, so adding a left alias on
'favorite.tag' does not turn the inner join of a restriction on 'favorite.label' into a left join. The
associations after it use the join type of the alias, as does the first one when nothing else joins it. The path
is relative to the root of the query that declares the alias, so a subquery does not pick up the outer query's
join.

This is the one feature of SubqueryAssociationCorrelationSpec that 8.0.x did not already pass after #16573. The
Hibernate 7 guide documents nested alias paths under Association Aliases.
jdaugherty added a commit that referenced this pull request Nov 5, 2026
Resolves the conflict in HibernateCriteriaBuilder with the createAlias
rework from #16573: keeps the one-join-per-alias logic from 8.0.x and
applies this branch's imports to it (Criteria, Basic, HibernateAlias).
@ruthst00

ruthst00 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@jdaugherty, @matrei, I'll work on the follow-up issues next. Thanks!

borinquenkid added a commit that referenced this pull request Nov 7, 2026
The association code that #16573 changed in PredicateGenerator now lives in AssociationCriterionHandler: a block resolves
its association through the context, takes the context of a QueryAliasRegistrar, and yields no predicate when it has
no criteria.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
borinquenkid added a commit that referenced this pull request Nov 7, 2026
…s-comparisons-8.0.x

Takes the review changes of #16816: the merge of 8.0.x with #16573, the subquery criteria joined with AND, the function list, the
rejection of a function over an rlike in a bulk statement, the package-private criterion handlers and the restored SPI documentation.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
borinquenkid added a commit that referenced this pull request Nov 7, 2026
…root-alias-nested-paths-8.0.x

Takes the merge of fix/h7-criteria-projection-immutability-8.0.x and the fix for a copy made while a deferred query runs. JpaCriteriaQueryCreator
creates its context through the QueryAliasRegistrar that #16573 introduced, as 8.0.x does, and registers the alias of the root right after it,
which this branch added.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
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.

Hibernate 7: createAlias joins the association twice, and ignores the join type for the alias

6 participants