Repository navigation
Hibernate 7: join each alias of an association path, and decide how blocks and aliases share joins (#16851, #16889) - #16891
borinquenkid wants to merge 41 commits into
Conversation
…queries Since #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>
With GORM for Hibernate 7, a sort by a property of an association read the property through the association path, which Hibernate joins with an implicit inner join. The sort left out the instances whose association is null, while the total count of a paged list still counted them. A sort must not change which rows a query returns, so each association on a sort path is now joined explicitly, with a left join unless the query already joins it or requests another join type for it. Where queries, detached criteria, dynamic finders and criteria queries resolve an order through ExpressionResolver.resolveSort, after the criteria, so that an order reuses the join the criteria have for an association. list builds its HQL with a left join for each association it sorts through. An order inside an association block of a criteria query was ignored, because only the orders of the root criteria reach the query. It now moves to the enclosing criteria, qualified with the association. This is the Hibernate 7 counterpart of #16853 for Hibernate 5.
A builder from createCriteria() kept the projections, aliases, paging and result mode of an earlier call, so a second query on the same builder returned a wrong result without an error. Only list replaced the criteria. tryCriteriaConstruction now starts every list, listDistinct, get, count and scroll call from a clean query (HibernateQuery.resetQueryState plus the builder's result-mode flags), and resets again if the call throws. list after list reuse keeps working.
A query that selects a property of an association with distinct, property or groupProperty and sorts by the same property was ordered through a second join of the association. A database rejects that for a distinct query, because the order is not in the select list. Such an order now sorts by the expression that the projection selects. An order in an association block by an alias that the block declares was moved to the enclosing criteria as <association>.<alias>.<property>, which does not resolve. It is now moved as an order by the path that the alias stands for. An order that names neither a property of the association nor an alias of the block stays in the block. A sort through an embedded component, such as details.author.name, still read the association inside the component through an implicit inner join, and left out the rows where it is null. The association is now joined with a left join, in criteria queries and in list.
An order in an association block by an alias that the block declares was moved to the enclosing criteria as an order by the path that the alias stands for. When the block declares two aliases of one collection, each alias has a join of its own, and the sort could use the join of the other alias. Such an order is now an AssociationAliasOrder, which keeps its block and the property as the block names it. PredicateGenerator records the context that the criteria of a block are built against, and the order is resolved against that context, so it sorts by the join of the alias it names. An order in the block of an embedded component threw an IllegalArgumentException: the property was looked up on the entity of the criteria of the block, and the class of a component is not a domain class. It is now looked up on the entity of the association, and the order sorts by the property of the component. A sort by a path reused the join that From.getJoins() returned first for an association, and that set has no order. With two aliases of a collection, an order by the path of the collection sorted by one alias at the root and by the other in an association block. A sort now reuses the first join that the query made for the association, which is the join that the path shares with its first alias.
The closure of and, or and not in a criteria query is evaluated by the detached criteria and not by the builder, so an order in an association block inside a junction stayed in its block and was ignored. The builder now moves the orders of the blocks inside a junction, at any depth, to the enclosing criteria once the junction is added. In such a block createAlias declares an alias with association criteria that have the alias, and not with a HibernateAlias, and an order by it is resolved against its block as well. The upgrade notes now describe a sort by a property of a collection, and say that the instances without the association can be on the first page of a paged list and be what first or a findBy finder returns.
An order of an association block had no effect while it stayed in its block. Moved to the root criteria, it reached queries that can only be ordered by what they select: listDistinct and queries with a distinct or aggregate projection ran before and were now rejected by the database. An order moved out of a block is an AssociationOrder, and in a query that selects distinct or grouped values or aggregates it is left out as before, unless the query selects its property. An order by an alias of a block was sorted by the expression of a projection that selects the path of the alias, which is the join of the path and not the join of the alias. Only a distinct or grouped query has to be ordered by what it selects, so in any other query the order sorts by the alias that it names. A sort by the identifier of an association, such as club.id, read the foreign key column without a join, and now joined the association. When the association is mapped as a many-to-one, which has its key in the table of the entity, the path is read as it is again, in criteria queries and in list. The JPA metamodel reports a hasOne association, whose key is in the other table, as a many-to-one too, so the mapping of the property decides. The join that a sort reuses is read from the joins that Hibernate keeps in order. The fallback to From.getJoins() was only reachable from unit specs that mocked From, which now mock Hibernate's types. The contexts of association blocks are recorded in a map that only the context of the query creates.
The rules that turn an order of an association block into an order of the enclosing criteria move to AssociationOrders. The criteria builder still applies them when a block ends. Criteria that are built in any other way, such as a detached criteria, keep the orders in their blocks, and the query now reads them from there, after the orders of the criteria themselves. An order in a block by an alias of the criteria around the block is resolved against the block, which sees that alias, and no longer ignored. A distinct list ordered by a property of an association was rejected by the database, since SQL orders a distinct query only by what it selects. Such a query is built without the keyword and its entities are made distinct once they are read, as with Hibernate 5. An order of an association block therefore sorts a distinct list too. An order by a property that does not resolve is rejected as an invalid sort property and no longer fails an assertion in Hibernate. Inside the block of an embedded component, an association block threw "Not an entity" and createAlias threw "is not a domain class". The builder takes the managed type and the entity of the component there. An inner join requested for a to-one association was only applied by the fetch join of a full-entity select. A count, the total count of a paged list and a projection query now join the association as well, so a paged list counts the rows that it returns. A sort reuses the fetch join of an association when the query has no other join of it, in criteria queries and in list. HqlListQueryBuilder validates a sort path and builds its joins in one walk. The methods that the unit specs call are public, or protected on the method invoker.
An order of an association block was resolved by its path from the root of the query, which does not tell the joins of one block from those of another. Two blocks of the same association share the join of that association and each join what is inside it, so an order in the second block sorted by the join of the first. Every order that comes out of a block now keeps its block and the property as the block names it, and is resolved against the context that the criteria of the block were built against. A sort takes the join that this context tracks for a path before any other join of the association. AssociationAliasOrder is removed, since an order by an alias is no longer the only order that needs its block. The closure of and, or and not was evaluated by the detached criteria, so an association block inside a junction was not a block of the builder, and its orders were added after the orders that were declared after it. The builder now evaluates the closure of a junction itself, as it evaluates every other closure of a criteria query. A block inside a junction is therefore the same as a block outside one: its orders keep the place they were declared in, a join type given to it is applied, and its association is fetched with the query. A distinct projection of an association that is ordered by a property of the association ran on 8.0.x and was rejected by the database, because the order had a left join of its own next to the join of the projection. An order now sorts by the expression of the projection when the query selects the property or the association that the property belongs to.
…g behind The reset ran when a call started, so it discarded maxResults, firstResult, criteria and uniqueResult set on the builder for that call, and it cleared the HibernateQuery that an earlier paged list still held for its total. The builder now replaces its HibernateQuery and clears the result mode when a call ends, in a finally, so a checked exception also resets it. A paged list keeps the query it was built from. lock, readOnly and cache set in a closure no longer reach the next call, because they live in the query that is replaced. The association block restores the builder's target class in a finally. Query.lock(false) took a pessimistic write lock; it now clears the lock. The createCriteria reference states the rule for Hibernate 7 and Hibernate 5. Claude-Session: https://claude.ai/code/session_01Dmki4Tgxp7dLBhzpe2xT93
…orms do
list() and singleResult() run the query the builder holds and left its restrictions in
place, so a later list { } kept both: eq('name', 'both'), list(), then
list { eq('name', 'x') } matched nothing, where the second call used to start clean.
Both now replace the query when they end, as every closure call does, so a criterion,
maxResults or uniqueResult set before the call applies to it and to nothing after it.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…achedCriteria, and reject it clearly on Hibernate 5 (#16851) AbstractDetachedCriteria.createAlias renamed the existing alias of a path when it was given another one, so the first alias was gone before any datastore saw the criteria. A second alias of a path is now kept as its own entry next to the first. Declaring the same alias again, or naming a block that had no alias, behave as before. Hibernate 5 joins an association once, as its Criteria API rejects a second join of one path. It used to reuse the join of the first alias for the second, so a restriction on the second failed with "could not resolve property". It now throws an InvalidDataAccessApiUsageException that names the association and both aliases. Aliases the query generates for associations nobody named are not affected. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…e H5 alias spec on the 8.0.x test setup (#16851) Hibernate 7 reads both aliases of an association path that the DetachedCriteria now keeps, and joins the association once for each. The pre-pass registers an aliased association entry only when the query does not already declare that alias in its own scope: a path has one join type in the criteria, so a second alias of the path would otherwise take the type of the last one, and an alias the subquery redeclares would be hidden by the enclosing query's. The Hibernate 5 spec added by the 7.0.x branch registers its entities with manager.domainClasses, which the 8.0.x test manager does not have; it uses registerDomainClasses here, as the other specs do. A merge of 7.0.x into 8.0.x conflicts on that line until the two branches are merged up together. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…x/h7-alias-consolidation-8.0.x # Conflicts: # grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/QueryAliasRegistrar.java
…-alias-consolidation-8.0.x
…) into fix/h7-alias-consolidation-8.0.x # Conflicts: # grails-data-hibernate7/core/src/main/groovy/grails/orm/CriteriaMethodInvoker.java # grails-data-hibernate7/core/src/main/groovy/grails/orm/HibernateCriteriaBuilder.java # grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/ExpressionResolver.java # grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PredicateGenerator.java
… path (#16851) The AliasMatrixSpec of the 8.0.x line showed that the error turned queries that returned rows on Hibernate 5 into exceptions: a second alias of a path that nothing restricts was harmless before, because the second alias simply reused the join of the first. Only a restriction on the second alias fails, with Hibernate's "could not resolve property". The translator is back to its old behaviour, and the spec pins what fails. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… switched-off tests (#16889) #16863 asserts that each of two blocks of one association sorts by the joins of its own block, and #16773 and Hibernate 5 make blocks of one association share a join, so the two disagree on the same query. The four features of #16863 that assert the per-block answer move out of AssociationSortSpec into AssociationBlockJoinDecisionSpec, next to three that record what the merged branch does today. Both groups are off until ALIAS_BLOCK_DECISION is set to shared or per-block, which lets either be tried, and the constant becomes a literal when #16889 is decided. Also fixes the import order and one indentation that the merge of #16863 into #16773 left in ExpressionResolver and HibernateCriteriaBuilder. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… into fix/h7-alias-consolidation-8.0.x
… association path (#16851) AbstractDetachedCriteria.createAlias replaces the alias of an association path when it is given another one. A MappingContext that implements MultipleAliasesMappingContext and says it joins an association once for each alias now gets every alias as an entry of its own, so the datastore sees both. A datastore that does not implement it, as Mongo, Neo4j, the simple datastore and Hibernate 5 do not, keeps the latest alias of a path, as it always has. The Hibernate 5 spec pins that: the second alias replaces the first, a restriction on it works, and a restriction on the replaced alias fails with Hibernate's own error. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… alias) into fix/h7-alias-consolidation-8.0.x
…#16851) HibernateMappingContext implements MultipleAliasesMappingContext, so a DetachedCriteria records each alias that createAlias declares for an association path and the pre-pass joins the association once for each. Other datastores do not implement it and keep the latest alias of a path, as they always have. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… after the first its own join (#16889) Blocks of one association that declare no alias share one join, as in Hibernate 5. The first alias of an association path shares the join of the path, and every alias after it has a join of its own, in the same criteria, in the same block or in another block. The query context records which alias has claimed the shared join of a path and passes the claim to the scopes around it, so an alias in a second block no longer joins what the alias of the first block joined. An order by a path in a block that declares an alias for the path sorts by the join of that alias. jdaugherty's alias-per-block feature stays as it was. His three features for unaliased blocks asserted that each of two blocks of an association had joins of its own, which the shared join makes a contradiction, so they are replaced by features that restrict both blocks to the same round and check which join an order sorts by, ascending and descending, in the first block, the second and a nested one. The documentation of the criteria builder states the rule. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…h7-alias-consolidation-8.0.x # Conflicts: # grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy
…s of its criteria (#16860) HibernateQuery.clone() no longer copies a separate list of aliases, because they are entries of the detached criteria that it clones. The spec that asserted the old list is replaced by one that asserts the entries are there in the clone and apart from the original. It fails when clone() drops them, which the CreateAliasJoinSpec pagination counts alone caught for one case only (basic collection aliases). Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…oes not define (#16858) A sort by an alias that the query does not define resolved to no expression, which failed with a NullPointerException or an AssertionError. assignOrderBy now throws IllegalArgumentException("Invalid sort property"), as for any sort property that names nothing, and the criteria guide says so. The spec covers the cases of the issue: a where query with a criterion on the association, one that defines another alias, a list without a criterion, a dynamic finder, a list that does not ignore case and an order of a detached criteria; a sort by an alias the query does define still sorts. It fails for four of the six cases when the order is ignored instead. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…othing (#16858) assignOrderBy left out the order of an association block that resolved to no expression, as every order of a block had no effect before they were sorted, while the same order outside a block threw. Ignoring it hid a misspelled property or alias, so it now throws IllegalArgumentException("Invalid sort property") in a block as anywhere else. The spec that pinned the old no-effect behaviour pins the rejection, and the criteria guide says an order that names nothing inside a block fails like any other. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…nct or grouped query cannot apply (#16858) assignOrderBy left out the order of an association block when the query could only be ordered by what it selects and the order was not selected, because the database would reject it. Leaving it out hid that the query was not sorted, so it now throws IllegalArgumentException saying that such a query can only be ordered by what it selects. The spec that pinned the old behaviour pins the rejection for a distinct and an aggregate projection, and the criteria guide says so. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…n undefined alias (#16858) The criteria guide said Hibernate 5 ignores such a sort. What Hibernate 5 does with it is decided in its own pull request, so the guide only says what Hibernate 7 does and how to avoid the failure. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…e projections to the association
Inside projections { }, an association block was a block of the builder, but the projections declared in it
were added to the query as properties of the root entity: projections { owner { property('name') } } projected
the name of the pet, not of its owner, and returned rows without an error. The builder now records the path of
the blocks that enclose a projection while a projections closure runs, and a projection declared in a block is
a projection of that property of the association. The block shares the join of the other blocks of the
association, so a block at the root and a block in projections read the same row of a collection.
AliasPathIdentitySpec turns the shapes of a large Hibernate 5 application into cases: the projection blocks, one
join spelled four ways, a full path that ends in the name of another association, a block in a subquery
correlated through an outer alias, the order overloads at the root, in or, in and and in a second build of a
detached criteria, and every order of four statements. The case that correlates a subquery through this.id
waits for the root alias of a subquery (#16821) and is marked pending.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…teria declared earlier (#14647) createAlias on a DetachedCriteria checked every segment of the path against the entities, so after createAlias('children', 'c') the path 'c.related' failed with "Argument [c.related] is not an association". It worked only when the alias had the name of its association, as in createAlias('children', 'children'). A path whose first segment is an alias the criteria declared earlier now continues the path of that alias, so 'c.related' is 'children.related', as the criteria builder resolves it. A first segment that is both an alias and a property of the entity names the alias. The Hibernate 5 spec covers both spellings. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…as in a DetachedCriteria (#14647) The two spellings of the chain, createAlias('children', 'c') then 'c.related', and the one where the alias has the name of its association, return the same rows. The first failed before the shared core resolved a path that starts with a declared alias. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…a declared alias) into fix/h7-alias-consolidation-8.0.x # Conflicts: # grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/DetachedCriteriaAliasSpec.groovy
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. A sort that names an explicit alias uses a different alias of the same association path. A detached join that starts from one of two aliases of the same association is rewritten onto the other alias, so a matching row is dropped.
| // the path of the association from the root, by which a join type is requested for it | ||
| String associationPath = ""; | ||
| int first = 0; | ||
| Join<?, ?> declaredAlias = tokens.length > 1 ? aliasJoin(from, tokens[0]) : null; |
There was a problem hiding this comment.
Input: an alias f for favorite, an alias favorite for likes, and an order by favorite.label. The sort uses f, so the order is the favorite's label instead of the like's label. Use the explicit alias when one has that name.
| String head = associationPath.substring(0, dot) | ||
| for (Query.Criterion criterion in criteria) { | ||
| if (criterion instanceof DetachedAssociationCriteria && ((DetachedAssociationCriteria) criterion).alias == head) { | ||
| return ((DetachedAssociationCriteria) criterion).associationPath + associationPath.substring(dot) |
There was a problem hiding this comment.
Input: two aliases of children, then a join from the second alias to related, with restrictions that match only that alias. The path is rewritten to children.related and the first alias's join is reused, so the parent is dropped. Keep the alias the join started from.
… an alias named like an association wins a sort
createAlias('c2.related', 'r') after two aliases of children was stored as children.related, so
r joined from the join of the first alias and a parent that matches only through the second was
dropped. The association criteria now remember the later alias a path starts from, the
registrar registers it as alias:rest as the criteria builder does, and the block of that path
joins from the alias and not from the path of its association.
An order by favorite.label sorted by the alias f when one alias was declared for the favorite
association and another was named favorite. An alias declared with the name of the first
segment is what the segment names.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@jamesfredley Both are fixed in 7ad2676, by cause. (1) A path that starts with the second alias of an association, |
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. A path that starts from a later alias is still joined through the first alias.
| // the first alias of an association names the path itself, so a path that starts with it is that path; a | ||
| // later alias is a join of its own, and a path that starts with it has to continue from that join | ||
| String pathFromAlias = startingAlias != null && !startingAlias.is(associationCriteriaMap[startingAlias.associationPath]) ? | ||
| writtenPath : null |
There was a problem hiding this comment.
Create aliases children as c1 and c2, then c2.related as r, then r.tag as t, and compare t.name with wanted. A parent whose first child has no related entity and whose second child's tag is wanted is dropped. r keeps the path from c2, but t is stored as the association path and joined through c1. Keep the starting alias when the path continues from an alias that already has one.
The fetch mode join of a list query is a left join (#16898), also where the query sorts through the fetched association and the fetch shares its alias. The upgrade guide entry about sorting by an association follows the entry about exception mappings. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16891 +/- ##
==================================================
+ Coverage 62.3608% 62.3794% +0.0185%
- Complexity 27306 27332 +26
==================================================
Files 2248 2248
Lines 111469 111492 +23
Branches 20422 20430 +8
==================================================
+ Hits 69513 69548 +35
+ Misses 32622 32610 -12
Partials 9334 9334
🚀 New features to boost your workflow:
|
jamesfredley
left a comment
There was a problem hiding this comment.
A path that starts from a later alias is no longer joined through the first alias when the path is that alias itself. Not approving. A path chained past that alias still follows the first alias, and a sort through a nested collection uses a different join from the restriction.
| associationPath = pathFromDeclaredAlias(associationPath) | ||
| // the first alias of an association names the path itself, so a path that starts with it is that path; a | ||
| // later alias is a join of its own, and a path that starts with it has to continue from that join | ||
| String pathFromAlias = startingAlias != null && !startingAlias.is(associationCriteriaMap[startingAlias.associationPath]) ? |
There was a problem hiding this comment.
createAlias('children', 'a'), createAlias('children', 'b'), createAlias('b.related', 'r'), createAlias('r.detail', 'd'), then eq('a.name', 'one'), eq('b.name', 'two'), and eq('d.name', 'wanted'). The parent is missing. d follows a, not r. Keep the starting alias when the path continues past it.
8.0.x now decides the joins of a query with JoinPlan and JoinPlanner (#16773), which replace the publish and inherit hooks this branch had in JpaQueryContext, ExpressionResolver and QueryAliasRegistrar. Those three take the 8.0.x design, and what this branch adds on top of it is carried over to it: - the sort expression of an order: resolveSort and its join helpers in ExpressionResolver, getSortExpression, isColumnOfRoot and the context of an association block in JpaQueryContext, which an order of a block sorts by - the first alias that declares a path in the whole query owns its join, and a later alias, in the same block or in another, has a join of its own: JoinPlan.own, JoinTracker.plannedOwner, used by the resolver - an alias whose path starts with another alias joins from the join of that alias - HibernateQuery keeps the aliases that createAlias adds, as 8.0.x does The Hibernate 7 core suite passes (4876 tests), and codeStyle. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
A path that starts from a later alias is no longer joined through the first alias when the path is that alias itself. Not approving. A path chained one hop further still follows the first alias, and a chain inside a junction does not see the alias declared there.
| associationPath = pathFromDeclaredAlias(associationPath) | ||
| // the first alias of an association names the path itself, so a path that starts with it is that path; a | ||
| // later alias is a join of its own, and a path that starts with it has to continue from that join | ||
| String pathFromAlias = startingAlias != null && !startingAlias.is(associationCriteriaMap[startingAlias.associationPath]) ? |
There was a problem hiding this comment.
createAlias('children', 'c1'), createAlias('children', 'c2'), createAlias('c2.related', 'r'), createAlias('r.related', 'rr'), then eq('c1.name', 'one'), eq('c2.name', 'two'), and eq('rr.name', 'x'). The parent is missing. rr follows c1, not r. Keep the starting alias when the path continues past it.
| return null | ||
| } | ||
| String head = associationPath.substring(0, dot) | ||
| for (Query.Criterion criterion in criteria) { |
There was a problem hiding this comment.
and { createAlias('children', 'c'); createAlias('c.related', 'r') } throws because c.related is not an association. The alias c was declared in the same block. Look in that block before rejecting the path.
🚨 TestLens detected 4 failed tests 🚨Test SummaryTip Inspect all details with the TestLens CLI: Groovy Snapshot Canary Build / Build Grails (shard 2) > :grails-data-hibernate7-core:test
🏷️ Commit: 6b2347c Test FailuresRLikeHibernate7Spec > test rlike works with #db > test rlike works with DB2 (:grails-data-hibernate7-core:test in Groovy Snapshot Canary Build / Build Grails (shard 2))SharedJoinTableHibernate7Spec > on #db a shared join table is unique per association > on DB2 a shared join table is unique per association (:grails-data-hibernate7-core:test in Groovy Snapshot Canary Build / Build Grails (shard 2))SharedJoinTableListHibernate7Spec > on #db two lists sharing a join table are written, read and kept unique by position > on DB2 two lists sharing a join table are written, read and kept unique by position (:grails-data-hibernate7-core:test in Groovy Snapshot Canary Build / Build Grails (shard 2))SharedKeyColumnHibernate7Spec > on #db several rows in each association of a join table with a shared key column are accepted > on DB2 several rows in each association of a join table with a shared key column are accepted (:grails-data-hibernate7-core:test in Groovy Snapshot Canary Build / Build Grails (shard 2))Rerun ControlsSelect tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
…a block or of a chain
An alias whose path starts with an alias declared inside an and, or or not block threw "is not an
association", because only the criteria outside a block were searched for the alias. An alias that
starts with an alias which itself continued from the second alias of a path, as rr after
createAlias('c2.related', 'r'), was joined from the first alias of the path instead of the join that
r names, so the query returned the rows of the wrong child.
The alias is now found in open and closed blocks, and an alias that continues from a continued alias
keeps the whole chain, as the criteria builder already does.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@jamesfredley Both cases reproduced, and are fixed in the new commit.
Not changed: the sort through a nested collection that uses a different join from the restriction, from your 17:14 review. I have not looked at it again in this round. Branch policy: the new public types ( If you find another shape that does not reproduce first time, a failing spec on a throwaway branch, or the few lines you ran, would help me a lot. |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A second alias of a collection still continues from the first alias.
| else if (keepsEveryAlias()) { | ||
| // A second alias of a path that already has one is another declaration, not a rename of the first: it | ||
| // is kept next to it, so both aliases reach the datastore, which decides whether they share a join. | ||
| associationCriteria = new DetachedAssociationCriteria(a.associatedEntity.javaClass, a, associationPath, alias) |
There was a problem hiding this comment.
children is aliased as c1 and c2. eq('c2.related.name', 'x') should follow c2. It follows c1, so a parent whose other child has that related name is returned. Keep the restriction on the alias it names.
|
@jdaugherty a question about your #16863 commit that this PR carries, after the dev@ thread "Fixes that change results on patch and minor branches". The thread agreed that a sort by an association that keeps the rows without it (the left join) ships behind a setting on the existing lines: off by default on 7.0.x, 7.1.x, 7.2.x and 8.0.x, on from 8.1.0, with one key for Hibernate 5 and 7 (the one #16853 will read), a note under the release, and a startup warning while it is off. Here it is not behind one: it changes the rows of every list sorted by a nullable association on 8.0.x. My plan is to leave the join-correctness parts in this PR, and to gate the sort part with the setting once its key is agreed in #16853, with the note in the guide. Do you prefer to gate it in #16863 yourself, or should I do it here on top of your commit and keep the authorship? |
Consolidates the open Hibernate 7 alias and join PRs into one branch, so the rules they disagree on are decided once. It contains #16890, the
7.0.xhalf, which should merge first.Fixes #16851
Fixes #16889
Fixes #16762
Fixes #16862
Fixes #16883
Fixes #16842
Fixes #16860
Fixes #16858
Fixes #14647
What is in it
This branch is rebased onto the join planner that #16773 merged. The alias rules are decided in one place, the
JoinPlanthatJoinPlannerbuilds for the whole query, andExpressionResolver,JoinTrackerandJpaQueryContextread from it instead of deciding on their own:JoinPlanrecords, for each association path, the join type, whether it was declared or only mentioned, and which alias owns the join (own,ownerOf). The first alias of a path in the whole query owns it, andJoinTracker.plannedOwnertells a later lookup whether an alias shares the path's join or has one of its own.alias:path, ascreateAlias('o.address', ...)inside a block is, is read to its absolute path before it is compared, so every spelling of one association is one join.Each of the following is merged with its own commits, so the authorship is kept:
On top of them:
HibernateMappingContextopts in to keeping every alias of an association path, so aDetachedCriteriawith two aliases of one path reaches the query with both (DetachedCriteria: a second createAlias of the same association path replaces the first alias #16851).projections { }an association block named an association, but the projections in it were added as properties of the root entity:projections { owner { property('name') } }projected the name of the pet and returned rows without an error. A projection in a block is now a projection of that property of the association, and the block shares the join of the other blocks of the association.DetachedCriteriaresolves an alias path that starts with an alias it declared earlier, as the builder does: aftercreateAlias('children', 'c'),'c.related'ischildren.related([3.1.4 + Hibernate4] DetachedCriteria throws error if more than one alias is created #14647, the core part is in Keep every alias of an association path in a DetachedCriteria when the datastore opts in (#16851) #16890).Invalid sort property: an order by an undefined alias, an order in a block that names nothing, and an order in a block of a distinct or grouped query that cannot apply it (Hibernate 7: a sort by an alias that the query does not define throws a NullPointerException #16858).Not in it
#16853 (the Hibernate 5 sort on
7.0.x) stays on its own and merges up. The original PRs stay open until this one is reviewed.Tests
The datamapping-core, Hibernate 5 and Hibernate 7 suites (4,876 tests in Hibernate 7 core, no failures) and the style checks pass, including the alias matrix of about 6,700 combinations against the Hibernate 5 rows. MongoDB, Neo4j and the simple datastore do not implement the opt-in, so
createAliasruns the code it always did there. This PR's CI is the first run of their suites on it.https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
Tracked in #16896.