Repository navigation
Fix for when H7 createAlias joins the association twice, and ignores the join type for the alias - #16573
Conversation
|
Thanks for the fix. Reading
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
}
}
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 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(_, _)
}
One smaller point from the same read: the two Happy to send this as a patch on top of your branch, or you can take it as it is, whichever you prefer. |
|
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 |
|
@borinquenkid, the refactoring is a great improvement! It definitely improves the cohesiveness, readability, and testability of the code. Thanks for this! |
|
@borinquenkid, @jdaugherty, are there any other changes you would like to this PR? Should it be retargeted to 9.0.x? |
jdaugherty
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 collectionschools. Please add the entity-collection case too, because it takes thegetOwnJoin(def.path())branch that the basic collection skips.createAlias('favorite', 'f', 1)withor { 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
QueryAliasRegistrarSpectests the package-privateQueryAliasRegistrarwith a mockedJpaQueryContext, andJoinTrackerSpeccallsgetOwnJoindirectly. The project guideline is to test through the public criteria API.CreateAliasJoinSpecalready does that well, so the mock-interaction specs mostly pin the refactor's shape rather than its behaviour.JoinTrackerkeeps aliases and association paths in the samejoinsByPathmap. An alias spelled like another property (createAlias('favorite', 'likes')) can therefore shadow a laterlikes { ... }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.
|
@sbglasius, I made your recommended changes in 7bc7691, ede40fe |
jamesfredley
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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:testsuite, run aftercleanTestwithout 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 ownTeam { Like favorite; hasMany likes: Like },Like { String label }andStudent { 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, andExpressionResolver.resolveFromAliasnow 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 entryfavoriteas the aliasfavorite.- Whether an alias was declared is guessed from its name,
explicitAlias = !alias.equals(def.path())(ExpressionResolver.java:129), socreateAlias('likes', 'likes')counts as implicit and never claims its join.QueryAliasRegistrar.discoveruses the same guess forinheritedPath(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.handleAssociationCriteriaand by step 3 ofresolveFromAlias, apart from the joins of named aliases. - Record whether an alias was declared.
QueryAliasRegistrarknows: aliases fromcreateAliasand from aDetachedAssociationCriteriaare declared, and the ones fromregisterDetachedJoinsand dotted-path discovery are implicit. A flag onHibernateAlias, or a set of declared names in the context, would do. Then the identity setexplicitlyAliasedJoinsand 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, andHibernatePagedResultList.getTotalCount()counts on a clone (HibernatePagedResultList.java:96).countResults()with projections builds itsJpaCriteriaQueryCreatorwithout 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 nulla 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
createAliascan delegate to the three-argument one with0(HibernateCriteriaBuilder.java:232-241). borinquenkid raised this in the first review. - Doc placement: the new section sits between Examples and Description on the general
createCriteriareference 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 covercreateAliasyet. 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,favoriteoroutsidejoins 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!isOwnDefinedcheck 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(1left,2right, anything else inner) and Hibernate 5'sJoinType.parse. - Header and
@since 8.0.1onQueryAliasRegistrarmatchprojectVersion=8.0.1-SNAPSHOT, and the new files carry no@authortag.
| /** | ||
| * Whether this query declares the alias, independently of any enclosing query. | ||
| */ | ||
| public boolean isOwnDefined(String alias) { |
There was a problem hiding this comment.
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.
| * 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) { |
There was a problem hiding this comment.
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().
ede40fe to
644adf8
Compare
|
@matrei, to keep the latest commit relatively simple, I resolved your first two sections:
...and left your other recommended changes for another commit that I will work on soon. All commits have been squashed into 644adf8 |
jamesfredley
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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[], withakept 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 withcount()and withlist(max: 1).totalCount(merge-base: 3, from the second join).tag { eq('name', 'a') }; likes { eq('tag.name', 'b') }, where bothTeamandLikehave atag, returns the matching team (merge-base:[], because the nestedtag.namereused the outertagjoin).
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.
jdaugherty
left a comment
There was a problem hiding this comment.
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 withcreateAlias('favorite', 'f'), and both variants are inCreateAliasJoinSpec. Resolved. - The association block inside a subquery has its test. Resolved.
createAlias('favorite', 'a', 1); createAlias('favorite', 'b', 0)with onlyareferenced 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') }withcount()andlist(max: 1).totalCount(2 here, 3 on the merge-base).tag { eq('name', 'a') }; likes { eq('tag.name', 'b') }withtagon bothTeamandLike(the matching team here,[]on the merge-base).
matrei
left a comment
There was a problem hiding this comment.
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:compileGroovyfails. See 1. - Local merge with the current
8.0.xtip, not pushed, with the fixes from 1 and 2: the full:grails-data-hibernate7-core:testsuite, run aftercleanTestwithout 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.xtip. - 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) andJpaQueryContext.resolveAssociation(JpaQueryContext.java:126) are only called fromorg.grails.orm.hibernate.queryand its specs. LikeisOwnDefinedandgetOwnJoin, 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 throwsCannot use comparison criteria on non-existent property [a.label](8.0.x:PathElementException). ADetachedCriteriakeeps one association criteria per path, and the secondcreateAliasrenames it. The guide already limits independent joins tocreateCriteria()andwithCriteria. A sentence saying that aDetachedCriteriakeeps only the last alias of a path would make that limit explicit. This could also be a follow-up. - Commits:
5eff154bbband735e492162have the same message again. Please squash on merge.
Verified as correct
- Separate namespaces:
JoinTrackernow holds only association-path joins andAliasRegistryonly named aliases.HibernateAlias.explicitreplaces the name comparison, andexplicitlyAliasedJoinsis gone.QueryAliasRegistrarmarks aliases fromregisterDetachedJoinsand dotted paths as implicit, and aliases fromcreateAliasandDetachedAssociationCriteriaas declared. - The issue's own case:
list(max: 10) { createAlias('likes', 'l'); eq('l.label', 'first') }.totalCountis2(8.0.x:3). - Unused basic-collection aliases: jdaugherty's four queries return the
8.0.xrows and counts ([grace, hank],2,[grace, hank, none],[grace, hank, none]), andBasicCollectionInQuerySpechas 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.xjoinslikestwice and returns[both, both, first only]. - Unreferenced entity aliases: the one
8.0.xresult I found that changes iscreateAlias('likes', 'a', 1); createAlias('likes', 'b'); likes { eq('label', 'first') }. The unreferencedbis now its own inner join, so a team with two likes comes back twice;8.0.xmakes 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:
hibernate7GuideFromRefis defined ingrails-doc/build.gradle:640, and both anchors exist:[[criteria]]in the H7 guide'sindex.adoc:172and[[criteriaAssociationAliases]]atcriteria.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.
747874a to
6d0f7bc
Compare
sbglasius
left a comment
There was a problem hiding this comment.
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.xtip.
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
discoverAliasesandregisterDetachedJoins: two blank lines remain beforeassignCriteria. - The second is the import matrei asked you to drop when resolving the conflict with #16758. Keep
Join, but dropJoinType, 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 bothwithCriteriaandDetachedCriteria.rowCount()with an unusedlikesalias gives the same count as on8.0.x. The eager materialization inQueryAliasRegistrar.createContextdoesn't change those existing results. HibernateQuery.clone()copyingaliases, and the projected count passing the owning query, look right. The pagination and count specs cover them.
6d0f7bc to
9003f57
Compare
|
@sbglasius, @matrei, thanks for your feedback. As you suggested I:
Please let me know if I missed anything :o) |
matrei
left a comment
There was a problem hiding this comment.
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:compileGroovyfails. See 1. - The head with the fix from 1 applied locally: it compiles,
checkstyleMainpasses, andCreateAliasJoinSpec,BasicCollectionInQuerySpecand theorg.grails.orm.hibernate.queryspecs pass (660 tests, 0 failures). At6d0f7bc808, which has the same logic, the full:grails-data-hibernate7-core:testsuite 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:126Please 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
createAliason 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.
a953d79 to
ba30bb7
Compare
|
@matrei, thank you for your patience. Here are the latest changes:
|
jamesfredley
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
c0e94eb to
48c7216
Compare
|
@matrei, thanks again. I made your final doc changes and squashed all commits. |
|
@jdaugherty, your review at
The code at You also mentioned two follow-up issues. I couldn't find them, and both still reproduce at
Are you still opening them? #16815 covers unresolved paths in property comparisons, but not these two. |
sbglasius
left a comment
There was a problem hiding this comment.
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)insideor { }no longer makes the disjunction always true.handleAssociationCriteriareturnsnullfor an empty association criteria after its context is built, anda left alias inside a disjunction does not override its restrictionscovers 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-514assertsrows.totalCount == 2twice. 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
createAliasinside 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 forcount { }afterlist { }). It would help to link them here once they are filed.
Approving.
…keeps its join type, and aliases are scoped to their own query.
de55345 to
7e0159f
Compare
|
@sbglasius, thank you for your review. I added a comment to |
borinquenkid
left a comment
There was a problem hiding this comment.
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:
-
#16559 overlaps this PR now. When jdaugherty checked, the files didn't overlap; at this head both PRs rewrite
handleAssociationCriteriaand touchAliasRegistry,ExpressionResolver,JoinTracker,JpaQueryContextand their specs. More than textual: this PR already honours nested block join types (QueryAliasRegistrar.createContexton the block registersgetJoinTypes()as implicit aliases, andresolveAssociationreuses only this context's joins), soowner(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. -
HibernateQuery.aliasesis now dead.createAliasno longer callsaddAliasand nothing else does, so theaddAllinclone()and thegetAliases()read inQueryAliasRegistrar.explicitAliases()carry nothing. Not wrong at runtime, so I opened #16860 for the cleanup rather than hold this PR.
Two non-blocking notes:
ExpressionResolver.resolveAssociationignores thejoinTypeit 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.
|
@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. |
✅ All tests passed ✅🏷️ Commit: 7e0159f Learn more about TestLens at testlens.app/docs. |
jdaugherty
left a comment
There was a problem hiding this comment.
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.handleAssociationCriteriareturnsnullfor an association criteria that has no criteria of its own, after its context is created, andgetPredicatesdrops it.a left alias inside a disjunction does not override its restrictionscovers the five-team example with the list,count()andtotalCount. - The reference page states the block-alias rule for Hibernate 7 and says how Hibernate 5 resolves the path.
isCountOnly()is identical to8.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.
|
The two follow-ups from my review are filed, both reproduced on
|
…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.
…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>
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.
…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.
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).
|
@jdaugherty, @matrei, I'll work on the follow-up issues next. Thanks! |
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
…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
…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
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
Validation
git diff --checkpassed.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
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