Repository navigation
Hibernate 7: cover the joins of nested association blocks in criteria queries - #16559
gustavoharff wants to merge 1 commit into
Conversation
|
While working on this PR I noticed that the Hibernate 7 criteria DSL only takes the join type of an association block or of 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 What do you think about also accepting 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 If it sounds good, I can open a separate PR for it. |
borinquenkid
left a comment
There was a problem hiding this comment.
Missing Changes to PredicateGeneratorSpec
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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 🚀 New features to boost your workflow:
|
borinquenkid
left a comment
There was a problem hiding this comment.
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,registerJoinTypeandgetLocalJoinTypeeach 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, soisNotEmpty('pets')next topets { ... }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.HibernateCriteriaBuilderNestedJoinTypeSpecchecks 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.
Dropped it in 6e74e9c.
Agreed, I'll open a separate PR with its own spec. For reference, |
jdaugherty
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
🚨 All tests passed but jobs failed 🚨Failed Jobs without Test Failures❌ CI / Neo4j Functional Tests (Java 21, indy=true) 🏷️ Commit: 1b7aba9 Rerun ControlsClick the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
jamesfredley
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 aDetachedCriteria, 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
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
|
@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>
043b018 to
aa2c948
Compare
|
@borinquenkid Rebased onto 8.0.x after #16573. It already covers the fix, so the PR is now tests only: |
|
The consolidation branch, now #16891, merges this PR, so your commit and its authorship are in it. All of your tests pass there unchanged: 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
left a comment
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
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 forface), 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
7.0.x): Bug fixes only. No new features or API changes.7.1.x): New features are welcome, but breaking existing APIs must be avoided.8.0.x): Reserved for major changes. Breaking API changes are permitted.Code Quality
./gradlew build --rerun-tasks../gradlew codeStyleand resolved any violations. See Code Style for details.Licensing and Attribution
Documentation
🤖 Generated with Claude Code