Skip to content

Hibernate 7: cover the joins of nested association blocks in criteria queries - #16559

Open
gustavoharff wants to merge 1 commit into
apache:8.0.xfrom
gustavoharff:fix/hibernate7-nested-join-type
Open

gustavoharff wants to merge 1 commit into
apache:8.0.xfrom
gustavoharff:fix/hibernate7-nested-join-type

Conversation

@gustavoharff

@gustavoharff gustavoharff commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

Tests for the joins of association blocks in Hibernate 7 criteria queries. This started as a fix for nested association blocks ignoring their join type (owner(1) { face(1) { ... } } rendered an inner join for face), but #16573 fixed that, so after rebasing onto 8.0.x only the tests remain.

Testing

  • 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.
  • :grails-data-hibernate7-core:test: 4478 tests, 0 failures.
  • ./gradlew clean aggregateViolations --continue: no Checkstyle, CodeNarc, PMD or repository convention violations.

Contributor Checklist

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.

🤖 Generated with Claude Code

@gustavoharff

Copy link
Copy Markdown
Contributor Author

While working on this PR I noticed that the Hibernate 7 criteria DSL only takes the join type of an association block or of createAlias as a number:

Pet.createCriteria().list {
    owner(1) {              // 1 = LEFT, 2 = RIGHT, anything else = INNER
        face(1) { ... }
    }
    createAlias('owner', 'o', 1)
}

On Hibernate 5 those numbers came from org.hibernate.sql.JoinType (JoinType.LEFT_OUTER_JOIN.joinTypeValue), but that class is gone since Hibernate 6, so on Hibernate 7 there is no named constant left to pass and code ends up with magic numbers.

What do you think about also accepting jakarta.persistence.criteria.JoinType?

owner(JoinType.LEFT) {
    face(JoinType.LEFT) { ... }
}
createAlias('owner', 'o', JoinType.LEFT)

The numbers would keep working as they do today, so nothing breaks for code coming from Hibernate 5. It would also match DetachedCriteria.join(String, JoinType), which already takes the JPA JoinType. The change is small: the association block check and createAlias in CriteriaMethodInvoker / HibernateCriteriaBuilder, plus tests.

If it sounds good, I can open a separate PR for it.

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

Missing Changes to PredicateGeneratorSpec

@codecov

codecov Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.5962%. Comparing base (0e8fd03) to head (1b7aba9).
⚠️ Report is 19 commits behind head on 8.0.x.

Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16559        +/-   ##
==================================================
+ Coverage     59.5770%   59.5962%   +0.0192%     
+ Complexity      25032      25026         -6     
==================================================
  Files            2175       2175                
  Lines          108651     108663        +12     
  Branches        19821      19821                
==================================================
+ Hits            64731      64759        +28     
+ Misses          34978      34960        -18     
- Partials         8942       8944         +2     

see 7 files with indirect coverage changes

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

borinquenkid
borinquenkid previously approved these changes Oct 10, 2026

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

The new head covers the production changes, so I'm withdrawing my change request. I went through each changed method against the specs:

  • AliasRegistry.getLocalDefinition, JoinTracker.getLocalJoin, JpaQueryContext.getLocalFrom, getLocalAliasDefinition, registerJoinType and getLocalJoinType each have a unit feature that shows the parent is not consulted (AliasRegistrySpec, JoinTrackerSpec, JpaQueryContextSpec). The join type feature also checks that registering a join type does not define an alias, so isNotEmpty('pets') next to pets { ... } still resolves to the property.
  • PredicateGenerator's association block now has a feature for each way it gets its join: reuse of the join its own context made, the join type of an alias definition, a join type recorded on the enclosing block, the default inner join, an outer block of the same name that must not be reused, and a subquery joining from its own root.
  • HibernateCriteriaBuilderNestedJoinTypeSpec checks the result rows through the DSL (left join kept, inner by default, projection count, collection restriction, subquery).

One non-blocking note: the definition.path() != null arm in PredicateGenerator is not exercised, and JpaCriteriaQueryCreator never registers a definition with a null path. Either drop the check or add a small feature for it, as you prefer.

On accepting jakarta.persistence.criteria.JoinType in the DSL: that sounds fine to me as an addition. I don't remember whether the DSL accepts Java types today, so it deserves its own PR with its own spec rather than riding on this one.

@gustavoharff

Copy link
Copy Markdown
Contributor Author

One non-blocking note: the definition.path() != null arm in PredicateGenerator is not exercised, and JpaCriteriaQueryCreator never registers a definition with a null path. Either drop the check or add a small feature for it, as you prefer.

Dropped it in 6e74e9c.

On accepting jakarta.persistence.criteria.JoinType in the DSL: that sounds fine to me as an addition. I don't remember whether the DSL accepts Java types today, so it deserves its own PR with its own spec rather than riding on this one.

Agreed, I'll open a separate PR with its own spec. For reference, DetachedCriteria.join(String, JoinType) already takes the jakarta enum. What's missing is the createCriteria/withCriteria builder, where association blocks (pets(LEFT_JOIN) { }) and createAlias only take the int constants. I'll wait for #16573 first, since createAlias ignores the join type until it lands (#16562).

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

I went through the change against the DSL plumbing (CriteriaMethodInvoker records the nested block's join type on the enclosing DetachedAssociationCriteria, and handleAssociationCriteria now reads it from there) and it does what the description says. Locally at 6e74e9c: HibernateCriteriaBuilderNestedJoinTypeSpec, PredicateGeneratorSpec, AliasRegistrySpec, JoinTrackerSpec and JpaQueryContextSpec pass, and the nested left join, the same-name blocks in either order, and the subquery root all come out as asserted. I also checked that the files this touches do not overlap with #16573, and that #16573 keeps the alias-definition path getLocalAliasDefinition relies on.

Two non-blocking notes inline, neither of which changes the outcome of the fix.

fromsByProvider.getRoot().join(definition.path(), definition.joinType()) :
fromsByProvider.getRoot().join(associationName, fromsByProvider.getLocalJoinType(associationName));
fromsByProvider.addFrom(associationName, associationRoot);
fromsByProvider.registerAlias(associationName, associationRoot);

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.

Is this line needed? With it removed, HibernateCriteriaBuilderNestedJoinTypeSpec (8), PredicateGeneratorSpec (44) and JpaCriteriaQueryCreatorSpec (26) all still pass. The old code only realized the association name as an alias when an alias definition existed for it; this realizes it for every block, so after the block the association name resolves through the alias registry of the enclosing context rather than through the join tracker. The join tracker already finds the join for a bare path (ExpressionResolver step 5), so I don't see what this adds. If it is there for a case I'm missing, a short comment saying which would help; otherwise I'd drop it to keep the alias registry to the explicit aliases, which is the same reasoning the comment below gives for registering join types rather than aliases.

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.

It is needed, for a case the specs didn't cover: a path through the association after a nested block, when an outer context has already realized an alias of the same name. In

Pet.createCriteria().list {
    eq('face.name', 'Santa')
    owner {
        face { isNotNull('id') }
        eq('face.name', 'Homer')
    }
}

the top-level face.name realizes face as the pet's face. Inside owner, resolveFromAlias takes the alias realized by the outer context (getRealized walks the parents) before it looks at the join tracker of this context, so without the line face.name resolves to the pet's face and the query returns nothing; with it, it resolves to the owner's face and returns Lucky.

You're right that it changes nothing at the top level: a block of the queried class always has a definition, and the old code realized it through resolveFromAlias. It only matters for nested blocks. I added this case to HibernateCriteriaBuilderNestedJoinTypeSpec and PredicateGeneratorSpec (both fail without the line) and a comment on the line in 1b7aba9.

// owner(LEFT) { face(LEFT) { ... } }, is recorded on this block's criteria. It is registered as a join type,
// not as an alias, so a criterion on the property of the same name, such as isNotEmpty('pets') next to
// pets { ... }, still resolves to the property rather than to the join.
associationCriteria.getJoinTypes().forEach(nestedContext::registerJoinType);

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 something for this PR to fix, but the claim here holds only when the property criterion comes before the block. With pets { eq('name', 'Rex') } followed by isNotEmpty('pets') inside the owner block, ExpressionResolver returns the join the block already made (step 5, the join tracker) and CriteriaBuilder.isNotEmpty throws ClassCastException: SqmSetJoin cannot be cast to SqmPluralValuedSimplePath. The same thing happens at the top level in either order, because a block of the queried class always records a join type and registerDetachedJoins turns that into an alias definition. All of this behaves identically on 8.0.x without this PR, so it is pre-existing, and the spec's criterion-first ordering is the right guard for what this change must not break. Could you narrow the wording to say the criterion still resolves to the property when it precedes the block? The resolver returning a join for a collection-valued path is worth a follow-up issue of its own.

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.

Agreed. I narrowed it to a criterion that comes before the block, here and in the Javadoc of JpaQueryContext.registerJoinType, which made the same claim. I'll open a follow-up issue for the resolver returning a join for a collection-valued path.

@testlens-app

testlens-app Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

🚨 All tests passed but jobs failed 🚨

Failed Jobs without Test Failures

❌ CI / Neo4j Functional Tests (Java 21, indy=true)

🏷️ Commit: 1b7aba9
▶️ Tests: 93074 executed
⚪️ Checks: 89/89 completed

Rerun Controls

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not approving. Nested join types and same-context reuse look right, and getLocalFrom does not reuse an outer join of the same name. The new alias registration undoes that for a subquery projection.

registerAlias realizes the association name. AliasRegistry.getRealized walks the parent registry. A subquery that projects owner.firstName therefore binds owner to the outer query's join when the outer criteria already has an owner { ... } block, even with no explicit alias. Projection translation runs before the subquery's own association block, so the subquery is silently correlated and the result depends on criterion order.

// eq('face.name', 'Santa') owner { face { ... } eq('face.name', 'Homer') }, is resolved against the aliases
// realized by the outer contexts before the joins of this one, so the join is realized as an alias of this
// context too.
fromsByProvider.registerAlias(associationName, associationRoot);

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 makes the association name visible to nested queries. AliasRegistry.getRealized (lines 74-78) returns the parent registry's realized join when the name is absent locally. ExpressionResolver.resolveFromAlias uses that lookup.

DetachedCriteria.for(Pet).build {
    owner { eq('active', true) }
    in 'id', DetachedCriteria.for(Pet).build {
        projections { property 'owner.firstName' }
    }
}

The subquery should project its own owner's first name. After this change owner resolves to the outer join, so the subquery is correlated and the rows change with the order of the criteria.

Keep an automatically realized association path local to the context that created it. Do not publish it as a correlation alias. An explicit alias that a subquery is meant to see can stay on the parent lookup. Please add a regression with an association block and an independent subquery projection of the same path.

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.

Thanks, you're right. I reproduced it: with an owner { ... } block in the outer criteria, a subquery projecting owner.firstName came out correlated (select o2_0.first_name from pet p2_0, person o2_0 where o2_0.id=p1_0.owner_id), both for a DetachedCriteria and for a subquery inside a nested block. Neither is correlated on 8.0.x, so the alias registration regressed it.

In 1b9594c the association block no longer realizes its join as an alias. It only records the join in the join tracker of its context. ExpressionResolver now resolves a path to a join made from the context's own root before it looks at the aliases realized by the outer contexts. That keeps face.name (and face) after face { ... } inside owner { ... } on the owner's face, which is the case the registration was added for, without publishing anything to a subquery. Explicit aliases still correlate as before.

Regressions added:

  • HibernateCriteriaBuilderNestedJoinTypeSpec: your example with a DetachedCriteria, and a subquery inside a nested block projecting a path through that block's association.
  • PredicateGeneratorSpec: an outer association block and a subquery projecting the same path.
  • ExpressionResolverSpec: a join from the context's own root winning over an alias the parent realized, and a subquery path not taken through a parent join that no alias defines.

One case still correlates, and it does on 8.0.x too: a top-level block in createCriteria. Every block there records a join type, and registerDetachedJoins turns it into an alias definition named after the path, which a subquery then sees through getDefinition and the parent JoinTracker. Fixing it means separating those automatic definitions from explicit aliases, so I opened #16762 for it rather than widening this PR.

I also merged 8.0.x, which brings #16758, the fix for the collection criterion next to its block that @jdaugherty pointed out.

@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. Nested association blocks keep the join type they ask for. Ordering by a projection alias that reuses the name of a join in the same query now orders by the join.

// 1. Check for materialized aliases (Materialized Selects/Joins), a join from THIS root first, for the reason
// given in resolveFromAlias
From<?, ?> local = joinTracker.getLocalJoin(cleanPath);
if (local != null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pet.createCriteria().list { owner { isNotNull('id') }; projections { min('owner.age', 'owner') }; order('owner') } materializes the owner join and then registers MIN(owner.age) under the same name. This return uses the join, so ORDER BY is the owner row rather than the aggregate and a strict-grouping database rejects the query. Prefer a join from this root over an alias inherited from an outer query, and keep a projection alias realized in this query ahead of that join.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This PR introduced that ordering, and it went away with the rebase. resolve() takes the realized alias first again, so order('owner') orders by the aggregate. It's covered in HibernateCriteriaBuilderNestedJoinTypeSpec.

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

Withdrawing my earlier approval, which was given at 6e74e9c and predates the later commits. Changing to request changes until the open concern from @jamesfredley is resolved: resolving an order() on a projection alias that shares its name with a join in the same query now picks the join instead of the projection.

@borinquenkid

Copy link
Copy Markdown
Member

@gustavoharff heads-up on sequencing with #16573. When jdaugherty checked, the two didn't share files. At its current head (7e0159f) #16573 rewrites PredicateGenerator.handleAssociationCriteria and touches AliasRegistry, ExpressionResolver, JoinTracker, JpaQueryContext and their specs, so they now overlap. More than textual: #16573 already honours nested block join types. QueryAliasRegistrar.createContext on the block registers its getJoinTypes() as implicit aliases, and resolveAssociation reuses only the joins of its own context, so owner(1) { face(1) { ... } } comes out as two left joins there as well.

#16573 has four approvals and CI is running, so the plan is to land it first. Once it's in, could you rebase this branch onto 8.0.x and drop what it then duplicates (the nested join-type registration and the same-name reuse guard), and keep what #16573 doesn't cover? The ExpressionResolver ordering fix for jamesfredley's order('owner') case looks like the main piece that stays, and HibernateCriteriaBuilderNestedJoinTypeSpec is worth keeping either way since it asserts the generated joins end to end. I'll re-review after the rebase.

…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>
@gustavoharff
gustavoharff force-pushed the fix/hibernate7-nested-join-type branch from 043b018 to aa2c948 Compare November 4, 2026 22:16
@gustavoharff

gustavoharff commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

@borinquenkid Rebased onto 8.0.x after #16573. It already covers the fix, so the PR is now tests only: HibernateCriteriaBuilderNestedJoinTypeSpec plus a few PredicateGeneratorSpec / ExpressionResolverSpec cases.

@gustavoharff gustavoharff changed the title Hibernate 7: honour the join type of nested association blocks in criteria queries Hibernate 7: cover the joins of nested association blocks in criteria queries Nov 4, 2026
@borinquenkid

Copy link
Copy Markdown
Member

The consolidation branch, now #16891, merges this PR, so your commit and its authorship are in it. All of your tests pass there unchanged: HibernateCriteriaBuilderNestedJoinTypeSpec, and the additions to PredicateGeneratorSpec and ExpressionResolverSpec. They sit next to the new alias rules from #16889, and none of them needed a change.

The branch is now #16891 (with #16890 for 7.0.x). Nothing for you to do, and you can close this PR once #16891 is merged, or earlier if you like.

@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. A nested block that does not ask for a join still reuses a left join from an outer block of the same name. The added case does not set that outer join, so it does not catch this.


expect: 'the face of the owner is joined from the owner, not taken from the face of the pet'
new DetachedCriteria(Pet).build {
face {

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.

With the pets from savePets(), join('face', JoinType.LEFT) and then owner { face { isNull('id') } } returns Rex. The owner has no face, so that row should be dropped. This case leaves the outer face block without a join type, so both joins are inner and the reuse is hidden. The nested block still takes the outer LEFT definition from the parent alias registry.

@github-actions
github-actions Bot dismissed borinquenkid’s stale review November 18, 2026 19:24

Dismissed automatically: the pull request changed after this approval, from 0110367 to aa2c948.

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.

4 participants