Repository navigation
Sort where queries by an association the query filters on - #16853
Conversation
jdaugherty
left a comment
There was a problem hiding this comment.
Verified locally on 0676c67 with :grails-data-hibernate5-core:test. The spec passes, and probes beyond it pass as well: a paged list(max: 2) with totalCount, max plus offset descending, .order('club.name', 'desc') on the detached criteria, a disjunction that uses the association (club.name == 'Arsenal' || name == '...'), a multi-key sort map mixing club.name and name, an explicit alias in the where query combined with a sort by club.name, and ignoreCase: false. The paged count works because HibernateQuery.clone() copies the criterion entries and the subcriteria but not the orders, so the count query carries no order by.
The change is right: getOrCreateAlias registers the join under both the association path and the alias, so resolving the order through criteriaAndAlias.alias covers the generated alias, the explicit alias and the association id in one place, and the detachedCriteria branch closes a latent NPE the old code had for a subquery-backed query. I also confirmed that a sort by an alias the query does not define is silently ignored (the else branch finds no such property), as the docs now say.
One thing to point out: the sort resolves a single association level only. A nested path such as team.club.name still throws, whether or not the where query joins it, while the new docs sentence reads as if any association path works. Details inline on order(). The other inline note is a merge-up heads-up for the Hibernate 7 docs on 8.0.x.
| Without an explicit alias, sorting on association properties may fail due to dynamically generated aliases. | ||
|
|
||
| For example the following query will fail: | ||
| To sort by a property of an associated entity, use the association path. This also works when the `where` query uses the same association: |
There was a problem hiding this comment.
Merge-up note: on 8.0.x the Hibernate 7 copy of this guide (grails-data-hibernate7/docs/src/docs/asciidoc/querying/whereQueries.adoc, section "Query Aliases and Sorting") still shows the owner.lastName sort as failing because of a dynamic alias, while the Hibernate 7 WhereQueryWithAssociationSortSpec there already expects it to work. The merge-up carries only this file, so that section stays stale unless it is aligned in the merge-up or a follow-up.
There was a problem hiding this comment.
Thanks. That section was never updated for Hibernate 7. I'll align it in a separate PR against 8.0.x, after checking the Hibernate 7 behavior a bit beyond what its spec covers.
| if (createdAssociationPaths.containsKey(sortHead)) { | ||
| // sortHead may be either an explicit alias or an association path that | ||
| // was joined (with a generated alias) by a where query criterion. | ||
| // Hibernate can only resolve the property through the alias. |
There was a problem hiding this comment.
This resolves one level only: property is split at the first dot, so a sort by a nested path such as team.club.name (Player -> Team -> Club) still throws a QueryException, whether or not the where query joins team.club. It threw before this change too, so it is not a regression, but the new docs sentence ("To sort by a property of an associated entity, use the association path") reads as if any depth works. Either extend this to nested paths, or state the one-level scope in the docs and leave nested paths to a follow-up.
There was a problem hiding this comment.
Right, it's one level only, as before. I've stated that in the docs now and would leave nested paths for a follow-up. Supporting them means walking the path, reusing the joins that the criteria register under the full path (such as team.club), and adding inner joins for the rest, which I'd rather not do on 7.0.x.
Explicit aliases don't help with nested paths either: the where DSL doesn't recognize def c = team.club, or def t = team; def c = t.club, as an alias, so a query that uses c doesn't compile.
There was a problem hiding this comment.
I'm actually going to fix this ...
There was a problem hiding this comment.
Pushed c0c5a80 to this branch. It reverts b494caa and makes order() walk the sort path one association at a time: a join the criteria registered under the full path, such as team.club, is reused, and each association not joined yet gets an inner join, so team.club.name sorts whether or not the where query joins it, and t.club.name works through an explicit alias of team. A sort by two properties of the same association no longer raises duplicate association path either, since the sort join is registered instead of created for every order. WhereQueryWithAssociationSortSpec covers the nested and duplicate cases (all six failed before the change), and the docs sentence now says the path can cross more than one association.
There was a problem hiding this comment.
@matrei I think it's worth doing this after looking at it. Take a look at the change and see what you think.
There was a problem hiding this comment.
Thanks, that looks good to me, and it brings Hibernate 5 in line with Hibernate 7, which already sorts by nested paths. I ran the grails-data-hibernate5-core tests on c0c5a80 locally, since CI didn't run them after I removed run ci, and they all pass.
Comparing a few queries before and after the change, the results are the same except for one: with fetch: [owner: JoinType.LEFT] on a nullable association, a sort by owner.name now keeps the rows without an owner, because the sort join uses the requested join type instead of an inner join. I think that's right, but since it changes results on 7.0.x, I'll mention it in the PR description.
matrei
left a comment
There was a problem hiding this comment.
I reviewed c0c5a80 and it looks good to me. Walking the path one association at a time and going through getOrCreateAlias reuses the joins the where query made. It also registers the sort's own join, which fixes the duplicate association path error for two sorts on the same association.
Two minor points, neither blocking:
- No test covers the
LEFTfetch join now being used for the sort. - The docs could say that a sort joins an association with an inner join unless
fetchasks for another type, so a sort byowner.nameleaves out pets without an owner. That was already the case before this change.
jamesfredley
left a comment
There was a problem hiding this comment.
Sorting by an association path reuses a join the where query already made and orders by that join's alias. A path through more than one association works the same way. Not approving. A sort by a nested identifier, such as team.club.id, inner-joins the last association and drops rows whose association is null. Those rows were returned before, because the identifier was ordered through the foreign key.
jdaugherty
left a comment
There was a problem hiding this comment.
Pushed 5e71443 for the feedback on c0c5a80.
@jamesfredley: a sort by a nested identifier keeps its rows again. team.club.id is sorted by the foreign key on team, as it was on 7.0.x, and club is joined only when there is no such foreign key. Details are in the thread.
@matrei: both points are in the same commit.
WhereQueryWithAssociationSortSpecnow covers the join type of a sort join: an inner join by default, which leaves out a team without a club, and a left join withfetch: [club: JoinType.LEFT], which keeps it.Team.clubis nullable in the fixture for that.- The docs say that an association is joined with an inner join unless the query requests another type, show the
fetchexample, and mention the nested identifier.
jdaugherty
left a comment
There was a problem hiding this comment.
Follow-up to my review above: 2154153 and 1b70845 replace the approach of 5e71443.
A sort should not change which rows a query returns, so an association that is joined only for a sort is now joined with a left join. That keeps the rows for every association on a sort path, so the foreign-key ordering for a nested identifier from 5e71443 is removed again.
@matrei: this goes beyond the two points in your review and changes results on 7.0.x, so I have updated the PR description and added section 22 to the upgrade notes.
- Where queries, detached criteria and dynamic finders (2154153): without a requested join type the sort join was an inner join, and a sort by
club.nameorclub.idleft out the teams without a club, from the list and from thetotalCountof a paged list. They are kept now. A join type requested for the association, such asfetch: [club: JoinType.INNER], is used for the sort, and an association the query has criteria on is still joined by the criteria.calculateProjectionPropertyNamein the same class already left-joins the associations it joins for a projection, for the same reason. list,findandfindAllwith an example,findWhere,findAllWhereand a criteria query with pagination arguments (1b70845) had the same inner join inGrailsHibernateQueryUtilsandGrailsHibernateUtil.Team.list(sort: 'club.name')left out the teams without a club, andfindAllWherewith that sort did not find such a team at all. They use a left join now too.- The where query docs say that sorting does not change which rows a query returns.
WhereQueryWithAssociationSortSpecand the newAssociationSortSpeccover it, and nine cases of each fail on c0c5a80.
@jamesfredley: the details for team.club.id are in the thread.
|
@jamesfredley @matrei @borinquenkid, a question that came up while testing this PR and that the PR does not change: what should the With four teams, one of which has no club (
"Fetched" is So in
It also means that The options I see:
What do you think should happen, and on which branch? The two rows where Hibernate 7 does not fetch look like a separate gap there. |
jamesfredley
left a comment
There was a problem hiding this comment.
A sort by a nested identifier such as team.club.id now left-joins that association and keeps the rows whose association is null. A paged criteria count can sort by a nested path, and each entry of a sort map is kept. Not approving. A sort stored on the query is applied before the list arguments, so an inner join requested there does not replace the left join the sort already created.
jdaugherty
left a comment
There was a problem hiding this comment.
Pushed b482d67, 4646683 and e6343c4 for the review of c6b4d61.
@jamesfredley: an inner join requested for the association now wins over a sort stored on the query, so Team.where { name == 'Unattached First Team' }.sort('club.name').list(fetch: [club: JoinType.INNER]) leaves the team out. A sort no longer joins an association when it is added to the query. The join is made when the query is executed, with the join type the query requests by then. Details are in the thread.
@matrei: 4646683 and e6343c4 go beyond the review and change results on 7.0.x again, so they are in the PR description, in the fetching guide and in section 23 of the upgrade notes. A join type other than LEFT that a where query, a detached criteria or a dynamic finder requests is now applied whether or not the query has criteria or a sort on the association. Before, Team.where { ... }.list(fetch: [club: JoinType.INNER]) fetched the club with an outer join and returned the teams without a club. Only a sort or a criterion on club made the inner join take effect, so a sort still changed the rows of such a query.
e6343c4 does the same for a criteria query. The criteria builder has accepted join('club', JoinType.INNER) since the join type was added to BuildableCriteria, and never used it: the method set a fetch mode like the one-argument join. A JoinType in the fetch argument of the builder's list matched no fetch mode and did not fetch at all. Both now join and fetch with the requested type.
jamesfredley
left a comment
There was a problem hiding this comment.
A requested inner join is applied when the query runs, and a nested identifier sort still keeps the rows whose association is null. Not approving. A subquery that both joins an association and filters through it fails with a duplicate association path, and a right join of a collection does not fetch that collection.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. A collection join that stands in for an inner join ignores a Hibernate filter, and a later join or select does not replace a requested inner join. A requested fetch of a collection is also dropped when another join traverses that collection. A subquery that joins an association and then filters through it no longer fails with a duplicate path. A right join of a collection now fetches it. Threads PRRT_kwDOAAfRJ86z71iD and PRRT_kwDOAAfRJ86z71iI resolved.
jdaugherty
left a comment
There was a problem hiding this comment.
Pushed six commits for the review of c5b0edb. The head is 9c59ac4.
@jamesfredley: the three points are fixed, and the details of the first two are in the threads.
- A join that is requested for a collection applies the filters of the session (6ce701e). The query is restricted with a subquery that joins the collection, instead of a check that the collection is not empty, so a shelf whose books all belong to another tenant is left out.
- A later
joinorselectreplaces a requested join type, in a criteria query and on a where query, and so does thefetchargument of a criteria query (b9f26d4). - A fetch that is requested for a collection is kept when another requested join traverses the collection (f4ef5b1). A path through a collection, as in
fetch: ['players.contract': JoinType.INNER], is now joined in the same kind of subquery and no longer in the query itself. That also makescountand thetotalCountof a paged list count instances instead of joined rows, and a criteria query return each instance once.
The other three commits come from a second pass over the branch:
- 71b4535: every join of a where query is made when the query is executed, with the join type that the query requests by then. A join type that the
fetchargument oflistrequests is now used for the join that the criteria or a projection of the query make. It was read after they had joined the association, soTeam.where { club.name == 'Chelsea' || name == 'Unattached First Team' }.list(fetch: [club: JoinType.LEFT])left out the team without a club. The join type of a nested association is looked up by its path, criteria on a nested association can be used more than once, and a sort stored on the query can be combined with criteria thatlistadds through an alias. - 8ef8631: a sort by two properties of one association no longer fails in
findandfindAllwith an example,findWhereandfindAllWhere, andlistjoins the association once for it. - 9c59ac4:
orderin a criteria query can sort by a property of an association. It failed, and with aQuery.Orderit sorted by a property of the queried class.
25 cases of AssociationJoinTypeSpec, WhereQueryWithAssociationSortSpec and the new MultiTenancyRequestedJoinSpec fail on c5b0edb, and 13 cases of AssociationSortSpec fail on b9f26d4.
@matrei: 71b4535, f4ef5b1 and 9c59ac4 change results on 7.0.x in a few more places. Sections 22 and 23 of the upgrade notes cover them, and the PR description is updated.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. An order by a collection leaves that collection unfetched even when the query asks to fetch it. An order by an association also leaves a requested inner join as a left join, so a team with no club is returned. A later join or select now replaces a requested join type, and a collection restriction uses the session filters.
jdaugherty
left a comment
There was a problem hiding this comment.
Pushed eight commits for the review of 9c59ac4. The head is cc58a3b.
@jamesfredley: both points are fixed in 4988d60, and the details are in the threads. order in a criteria query joined the association of its property at once, before the rest of the criteria and the fetch argument of list were known. The criteria builder now adds its orders once the criteria are built, after the join types that they request. An order therefore uses the join type that is requested for its association, and a collection that the criteria ask to fetch is fetched. This holds whether the request comes before or after the order.
97bd0e5 makes the same change for find and findAll with an example, findWhere and findAllWhere, where a sort by a property of a collection did not fetch the collection when the fetch argument asked for it.
The other six commits come from another pass over the branch:
- 5a94a73:
order('club.id')in a criteria query makes no join again and reads the foreign key. Since 9c59ac4 it joinedclub, and a query withprojections { distinct('club.id') }and that order failed. - 7e847ed: inside the criteria of an association,
order(Query.Order.asc('name'))sorts by the property of that association, asorder('name')does. It sorted by the property of the queried class. - 75b5b4d: a where query that has criteria on a collection and requests
JoinType.LEFTfor it no longer fetches the collection through the join of the criteria. That join only has the elements that the criteria match, soTeam.where { players { name == 'A' } }.list(fetch: [players: JoinType.LEFT])returned the team with one player in the collection. The collection is now loaded when it is read. - 60450f9: the subquery of a requested join has a short alias. The alias was made from the association path, and Hibernate uses it as it is in the SQL.
- e8f7036: two corrections in the fetching guide and the upgrade notes.
- cc58a3b:
updateAllanddeleteAllapply a requested join type.Team.where { ... }.join('club', JoinType.INNER)listed and counted the teams with a club, butupdateAllanddeleteAllon it also updated or deleted the teams without one. An update and a delete cannot join, so each requested join is applied to them as a subquery restriction.
28 cases of AssociationJoinTypeSpec and AssociationSortSpec fail on 9c59ac4, and nine cases for updateAll and deleteAll fail on e8f7036.
@matrei: 97bd0e5, 7e847ed, 75b5b4d and cc58a3b change results on 7.0.x. Sections 22 and 23 of the upgrade notes have an entry for each, and the PR description is updated.
jdaugherty
left a comment
There was a problem hiding this comment.
One more commit since the review above. The head is 1ab83ab.
updateAll and deleteAll apply a requested join type with a subquery (cc58a3b). For a path that leads back to the queried class, such as the parent of a category, that subquery selects from the table that the update or the delete modifies. MySQL, and MariaDB before version 10.3, do not allow that, so the statement failed there with an error of the database. With 1ab83ab, updateAll and deleteAll throw an UnsupportedOperationException on these databases. It names the association and says to restrict the query with criteria instead, as in Category.where { parent != null }. Other databases run the statement.
RequestedJoinBulkOperationDialectSpec covers this with the MySQL and MariaDB dialects, and four of its nine cases fail on cc58a3b. The fetching guide and section 23 of the upgrade notes describe it.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. A listener that adds an association restriction to findAll is ignored, and the query fails to resolve the alias. Sorting an example query by an association still returns a row whose association is null when an inner join was requested. A criteria list that asks to fetch a collection it sorts by now fetches it.
jdaugherty
left a comment
There was a problem hiding this comment.
Pushed two commits for the review of 1ab83ab. The head is 0c81f00.
@jamesfredley: both points are fixed in 688440e, and the details are in the threads. A listener's criteria on an association now get their joins after the PreQueryEvent, and find and findAll with an example, findWhere, findAllWhere and list apply a JoinType in their fetch argument, before a sort by the association, which uses that join.
A second review of the branch, with each finding run against 7.0.x, found seven more regressions. The same commit fixes them:
deleteAllwith an inner join of a collection that has a join table deleted no instance and removed the join rows of the instances it should have deleted. Hibernate deletes the join rows first, with the same restriction. The identifiers are now selected first.updateAllanddeleteAllmatched the side of a one-to-one that the other class has the foreign key of, asNose.facewithstatic belongsTo = [face: Face], by comparing the two primary keys, and changed other instances thanlistreturns.- A sort by a collection that has a join table and multi-tenant elements produced SQL that no database accepts: Hibernate combines the condition that keeps the collection from being fetched with the tenant filter of the join table. The condition is now part of the where clause.
- A sort by
players.namein a query that fetchedreserves, a collection of the same class, filledreserveswith the players. The sort now fetches its collection as well when the query fetches another one. join('club', JoinType.LEFT)followed byfetch: [club: 'join']lost the left join for the criteria onclub, as on 7.0.x it did not.- A paged criteria query sorted through an alias, as
sort: 't.club.name', lost its sort. - A nested sort path was resolved through an alias of the criteria that has the name of the first association on the path.
0c81f00 fixes older issues that the review found in what this branch changes or documents: order('contract.id') on a hasOne inner-joined, a paged criteria query with a map of sort properties failed, a projection into an embedded component of an association failed, a right join of a collection that criteria join returned null rows, a join type for a collection of a basic type was ignored, and the associations before a collection on a requested path were not fetched. It also corrects two statements in the docs.
50 of the new cases fail on 1ab83ab. The whole test suites of grails-data-hibernate5-core and grails-datamapping-core pass, and so does codeStyle for both.
@matrei: both commits change results on 7.0.x in a few more places, and sections 22 and 23 of the upgrade notes describe each of them. grails-datamapping-core gains getSupersededJoinTypes() on the detached criteria, so that a join type that a later fetch mode replaced still reaches the query. The PR description is updated.
|
@jdaugherty thanks for the split, and for keeping 7323d92. I checked the reset: its five commits are the ones at 5e71443 ( On 11-17 I said that after the reset I'd make a join that only the sort needs an inner join again, and take the
On 7.0.x the sort overrides the join type that the call asks for: the query requests a left join, gets an inner one, and loses a row that it returns without the sort. That's the wrong-result case of the rule in #17061, so the fix goes to 7.0.x. It doesn't need a setting, since Hibernate 7 already returns the new rows for the same call. The stack agrees: at #17073 with Item 1 therefore changes a result, not only queries that threw, and needs what the rule asks for. I'll add:
It also needs a second reviewer. The |
A where query, a detached criteria or a dynamic finder that requests a left join of an association and sorts by a property of it now returns the instances without the association, and the totalCount of a paged list counts them. Grails 7.0.17 left them out, because the sort joined the association again with an inner join. Add a note under Grails 7.0.18 to the upgrade guide, and the same entry to the upgrade skill.
✅ All tests passed ✅🏷️ Commit: 7bad57e Learn more about TestLens at testlens.app/docs. |
codeconsole
left a comment
There was a problem hiding this comment.
No blocking defects. Left a few optional notes inline on a trailing-dot split edge case and test coverage for the tie-breaker sort key and the documented join(..., JoinType.LEFT) / totalCount case.
| * sorted by its foreign key instead, as a join would leave out the rows where the association is null. | ||
| */ | ||
| private String calculateSortPropertyName(String property) { | ||
| String[] tokens = property.split("\\."); |
There was a problem hiding this comment.
Optional: property.split("\\.") drops trailing empty segments, so malformed input like 'club.' yields a single-element array, skips the loop, and produces 'null.club' (or 'club_alias0.club' when already joined). property.split("\\.", -1) avoids that.
| when: | ||
| final results = Team.where { | ||
| name ==~ '%First%' | ||
| }.list(sort: ['club.name': 'desc', 'club.id': 'asc']) |
There was a problem hiding this comment.
Optional: all three clubs have distinct names, so 'club.id': 'asc' never breaks a tie here. This verifies the duplicate association path fix, and adding a tie on the first key would also prove the second order is applied.
| when: | ||
| final results = Team.where { | ||
| name ==~ '%First%' | ||
| }.list(sort: 'club.name', fetch: [club: JoinType.LEFT]) |
There was a problem hiding this comment.
Optional: the upgrade note highlights join(..., JoinType.LEFT) and totalCount on a paged list in addition to fetch: [club: JoinType.LEFT]. Testing a paged call (max: 10) and checking totalCount (plus join('club', JoinType.LEFT)) would directly lock in that behavior change.
|
With Scott's approval, I think this is ready to merge. I'm not seeing anything blocking. This has been open for awhile and we've done a lot of work off this. I'm going to merge and we can iterate on any follow-ups. @matrei let me know if you disagree and i'm happy to revert after the merge. |
list with a map of sort properties, such as Team.list(sort: ['club.name': 'asc', name: 'desc']), sorted by the last entry only, because each entry replaced the orders of the query. The same held for a default sort that the mapping declares for more than one property. Every entry is now applied, in the order of the map. An association is joined once for all the sort properties that use it. list joined it once for each, and find and findAll with an example, findWhere and findAllWhere failed with "duplicate association path". Part 2 of the split of #16853.
A paged query of a detached criteria that has an alias for the queried
class, and criteria that use it, failed when totalCount was read:
new DetachedCriteria(Team, 't').eq('t.name', 'Arsenal').list(max: 2).totalCount
The count runs on a copy of the criteria, and the copy was created
without the alias, so Hibernate could not resolve t.name. The copy now
has the alias of the original.
Part 3 of the split of #16853.
count on a where query or a detached criteria that has a sort, such as
Team.where { ... }.sort('name').count(), kept the order by in the query
that counts the rows, which H2 rejects with "must be in the GROUP BY
list". A query that only counts its rows now has no orders.
The join that a sort by a property of an association makes is kept, so
the count is that of the rows which list returns for the same query.
Part 4 of the split of #16853.
… by it A sort by a property of an association joins the association with an inner join, so it leaves out the instances whose association is null: Team.list(sort: 'club.name') does not return the teams without a club, and count and the totalCount of a paged list do not count them. The new grails.gorm.leftJoinAssociationSort setting makes an association that is joined only for a sort a left join, in where queries, detached criteria, dynamic finders, list, find and findAll with an example, findWhere, findAllWhere and a criteria query that is passed pagination arguments. It is disabled by default, so the results of existing applications do not change in a patch release. Grails 8.1 enables it by default. With the setting, a sort by a nested identifier, such as team.club.id, goes through the left join. Without it, it is still read from the foreign key. A sort by a property of a collection keeps its inner join: Hibernate fetches a collection through a left join, which is handled separately. Part 5 of the split of #16853.
A where query, a detached criteria and a dynamic finder joined an association as soon as criteria, a projection or a sort needed it. The rest of the query can still change after that: criteria passed to list are added later, and the fetch argument of list, which can request a join type, is read last. The result depended on the order in which the query was put together: - a join type in the fetch argument of list was not used for the join that the criteria or a projection had already made; - a sort stored on the query with sort() was joined before a join type requested in list was known, and criteria passed to list could not join the same association through an alias; - a join type was looked up by the name of the association, so a type requested for club was used for team.club, and one requested for team.club was not; - criteria on a nested association used twice failed with "duplicate association path". Criteria, projections and orders only need the alias of a join. A join is now registered under its path from the root entity and its alias, and made when the query is executed, or when a subquery is handed to the query that embeds it, with the join type that the query requests for that path. A listener of the query events that adds criteria on an association to find and findAll with an example, findWhere or findAllWhere gets its joins made after the event. Part 6 of the split of #16853.
|
@jdaugherty no disagreement, thanks for merging it. Scott approved the head, and the result it changes is what Hibernate 7 on 8.0.x already returns, so the merge-up keeps the two modules together. My comment of 11-20 asked for a second reviewer, and for me Scott's approval and your rounds on my commits cover that. CI last ran here on 11-20, and the merge push didn't run the tests, so I ran them at the merge commit, 165ba77. The With #17062 to #17066 in, the 7.0.18 note of this pull request needs two edits, and a third when #17069 and #17071 land:
None of the open parts has merged 7.0.x since this merge, so the edits could go into #17067 when it does. Or I can open a docs pull request for them once the stack is in, whichever you prefer. |
A where query, a detached criteria or a dynamic finder can request a
join type for an association, with fetch: [club: JoinType.INNER] or
join('club', JoinType.INNER). The type was only used when criteria or
a sort joined the association. Otherwise the association was fetched
with the outer join of its fetch mode, so
Team.where { ... }.list(fetch: [club: JoinType.INNER]) returned the
teams without a club, and the same query sorted by club.name did not.
A requested join type other than LEFT is now applied when the query is
executed, to list, get, find, count, the totalCount of a paged list, a
subquery and a query with a projection:
- INNER and RIGHT on an association to a single instance join and
fetch it; a right join is a right join, not an outer fetch;
- a path that ends in a collection or passes through one restricts the
query with a correlated subquery, so that the collection stays
fetched with all of its elements, each instance is counted once, and
the filters of the session, such as the tenant filter, apply;
- every association on a requested path is joined and fetched;
- a collection of a basic type is handled like any other collection;
- a fetch mode requested afterwards replaces the join type, on the
query and on the detached criteria, while the join that criteria on
the association make keeps it.
Part 7 of the split of #16853.
Team.where { ... }.join('club', JoinType.INNER) lists and counts the
teams with a club, but deleteAll and updateAll on it ignored the join
type and deleted or updated the teams without a club as well. They now
modify the instances that list returns.
An update or a delete cannot join, so each requested join becomes a
restriction: a subquery that selects from the entity of the first
association on the path and joins the rest of it. deleteAll selects the
identifiers first when the path starts with a collection that has a
join table, because Hibernate deletes the join rows before the
instances with the same restriction. A one-to-one whose foreign key the
other class has is matched through the property that refers back.
MySQL, and MariaDB before 10.3, do not allow an update or a delete to
select from the table that it modifies. For a join that leads back to
the queried class, these dialects get an UnsupportedOperationException
that says to restrict the query with criteria instead.
Part 8 of the split of #16853.
The criteria builder accepted a join type and never used it.
join('club', JoinType.INNER) has had the body of the one-argument join
since it was added, so it set a fetch mode, and a JoinType in the fetch
argument of list matched no fetch mode, so the association was not
fetched at all.
Both now join and fetch the association with the requested type, with
the rules of a where query: a path through a collection restricts the
query with a subquery, and the associations on the path are fetched.
The join types are applied once the criteria are built, so an
association that the criteria have a block for, or join through an
alias, keeps that join. A fetch mode requested afterwards, with join,
select, fetchMode or the fetch argument, replaces the join type.
The sort argument of the list of a criteria query uses a join that the
criteria already have for the association, such as the one of a join
type that the fetch argument requests for it. It joined the association
a second time, which failed with "duplicate association path".
Part 9 of the split of #16853.
The sort now matches the Hibernate 5 parts on 7.0.x (#16853, #17062, #17064, #17065 and the approved #17070) and nothing beyond them: - A sort by a property of a collection joins it with an inner join with or without leftJoinAssociationSort, as merged Hibernate 5 does; the left join with the setting is #17072, still under review. - An order in an association block of a criteria query becomes an order by the path through the association when the block ends, and sorts through the join of the block, as with Hibernate 5. AssociationOrder, AssociationOrders and the per-block contexts are removed, and with them the orders by aliases of a block or of the criteria around it. - Orders in the blocks of a detached criteria that the builder did not build, and in the block of an embedded component, are ignored, as with Hibernate 5 and on 8.0.0. Sorts through an embedded component are read as a path, as on 8.0.0, and the fixes for blocks inside an embedded block are removed. - A block order in a distinct, grouped or aggregate query reaches the database, as with Hibernate 5, instead of being rejected beforehand. - grails.gorm.PagedResultList and the TCK DetachedCriteriaSpec are back as on 8.0.x. HibernateQuery.clearOrders() keeps the cleared orders, whose joins a count still makes, as Hibernate 5 keeps the alias that an order joined. - The new methods of ExpressionResolver and JpaQueryContext are package-private.
A sort that starts with the alias that a detached criteria gives the queried class, as in new DetachedCriteria(Team, 't').list(sort: 't.name'), was ignored: the query returned its rows unsorted, without an error. Such a sort now sorts by the rest of its path, in where queries, detached criteria, list, the example queries and the sort argument of a criteria query. Part 13 of the split of #16853.
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 apache#16853 for Hibernate 5.
order('club.name') in a criteria query failed with "could not resolve
property", and with a Query.Order it sorted by a property of the
queried class. A criteria query that is passed pagination arguments
and a sort by a path through more than one association failed when
totalCount was read, or with "duplicate association path" when the
criteria used the first association, and a map of sort properties
failed with a ClassCastException.
order now resolves an association path, also inside the criteria of an
association, and joins with a left join an association that the
criteria do not join. The orders are added once the criteria are
built, so an order uses the join and the join type that the criteria
or the fetch argument request, whichever comes first. An order by the
identifier of an association reads the foreign key, as before. The
sort argument reuses a join that the criteria have for a path, also
one made through an alias, and creates any other from the root
criteria, which is how the count recreates it.
The sort argument can also start with an alias that the criteria give
an association, as sort: 'c.name' with createAlias('club', 'c'), also
as an entry of a map of sort properties and followed by a further
association. Such a sort was dropped, which review 5868034911 of
apache#16853 reported for the map.
The join that an order makes is a left join only with the
grails.gorm.leftJoinAssociationSort setting. Without it the association
is joined with an inner join, as it is for the other sorts.
Part 10 of the split of apache#16853.
list, findWhere, findAllWhere, and find and findAll with an example ignored a JoinType in their fetch argument: they returned the instances without the association, and list did not fetch it. They now apply it, before a sort by the association, which uses that join. list fetches with the requested type, returns each instance once when it fetches a collection, and applies RIGHT like INNER, since Hibernate does not support right joins in the criteria queries that list runs. 'join' and 'eager' in the fetch argument of list fetch the association with a left join and return every instance, as a where query and a dynamic finder do. list joined it with an inner join without fetching it, so it left out the instances whose association is null or whose collection is empty. The totalCount of a paged list counts each instance once when the list fetches a collection, and keeps a sort join that hangs under a fetch. Part 11 of the split of apache#16853.
A sort by a property of a collection joined the collection with an inner join. It left out the instances whose collection is empty, and took the place of a fetch that the query requested for the collection. Criteria on a collection with a requested left join initialized the collection with only the elements that the criteria matched. - A sort joins a collection with a left join and does not fetch it through that join, unless the query asks for the collection to be fetched, with or without the sort. - A left join of a collection that criteria use does not fetch the collection. When the query also fetches another collection, that one is loaded once the query has run, because Hibernate would read it from the columns of the join of the criteria. - A sort by a collection next to a fetch of another collection repeats rows, and a bag cannot tell a repeated row from a repeated element, which is why Hibernate does not fetch two bags in one query. When either collection is a bag, the query throws an UnsupportedOperationException that names both, where it returned the bag with repeated elements. A query that projects values loads no collection and is not affected. A fetch that a mapping declares counts as fetched only where Hibernate joins it: not at or beyond hibernate.max_fetch_depth joins from the queried class, where Hibernate loads it with a query of its own (review 5868034911 of apache#16853). This applies with the grails.gorm.leftJoinAssociationSort setting. Without it a sort still joins a collection with an inner join, which leaves out the instances whose collection is empty. Part 12 of the split of apache#16853.
Description
Fixes #15589. This is part 1 of the split of this pull request, as agreed here and in the dev@ thread Fixes that change results on patch and minor branches. Parts 2 to 13 are #17062 to #17073, stacked on this one, part 14 is #17074 on 9.0.x, and #17079 gives Hibernate 7 the rule of the requested join types. The previous head, 7323d92, is kept at
preserve/16853-full.Sorting a where query by a property of an association failed with a
QueryExceptionwhen the query also had criteria on that association:The criteria join
clubunder a generated alias, such asclub_alias0, andAbstractHibernateQueryrecords the join under both the association path and the alias.order()found the join, but added the order with the association path, which Hibernate cannot resolve against the root entity. The sort only worked with an explicit alias defined in the where query, because then the sort property already started with the alias. The order is now added with the alias of the join, asclub_alias0.name.A sort by a path through more than one association, such as
team.club.name, failed whether or not the where query joined the nested association, becauseorder()split the path at its first dot only.order()now walks the path one association at a time. It reuses a join that the criteria registered under the full path, such asteam.club, and joins any other association on the path for the sort, registering that join like any other. A sort through an explicit alias, such ast.club.name, works the same way. Because the sort join is registered instead of created anew for every order, a sort by two properties of the same association no longer fails withduplicate association path.A sort by the identifier of an association that follows another one on the path, such as
team.club.id, is sorted by the foreign key of the association before it, so it keeps the players whose team has no club, as a where query without criteria onteamalready did on 7.0.x. An association without such a foreign key, ahasOneor the inverse side of a one-to-one, is joined.Sorting by an explicit alias gives the same order as before, and so does sorting by the identifier of an association, such as
club.id, in a query with criteria onclub, which now goes through the join instead of the foreign key.The "Sorting with Associations" section of the where query docs said that this sort fails and that an explicit alias is required. It now shows the sort by the association path, says that the path can cross more than one association, that an association is joined with an inner join unless the query requests another join type, how to request a left join, and how the identifier of a nested association is sorted.
Results that change
join('club', JoinType.LEFT)orfetch: [club: JoinType.LEFT], and sorts by a property of that association, returns the instances without the association, and thetotalCountof a paged list counts them. Grails 7.0.17 left them out, because the sort joined the association again with an inner join, although the same query without the sort returned them. With three teams, one of them without a club,Team.where { name ==~ '%First%' }.join('club', JoinType.LEFT).list(max: 10, sort: 'club.name')returns 2 teams on 7.0.x, and 3 with this change and with Hibernate 7 on 8.0.x.JoinType.INNER, or add a criterion such asclub != null.listand criteria queries with the samefetchargument still leave the instances out, until Apply a join type that a criteria query requests #17069 and Apply a join type in the fetch argument of list and the example queries #17071.Apart from this, only queries that failed before behave differently. A sort by an association for which the query requests no join type still joins it with an inner join, as on 7.0.x.
The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry. As a fix that changes a result, this needs two reviewers.
Tests
WhereQueryWithAssociationSortSpecasserted theQueryException. It now checks:club.namewith criteria onclub, ascending and descending, with a sort map and with chainedwherecalls, and byclub.id, by an explicit alias, and byclub.namewithout criteria onclub;clubwhen the query has no criteria on it;Playerbyteam.club.namewith criteria onteam.club, onteamonly and on neither, and byt.club.namethrough an explicit alias ofteam;club.nameleaves out a team without a club, and keeps it whenfetchrequests a left join;team.club.idkeeps a player whose team has no club, also through an explicit alias and with criteria onteam, and that a sort by the identifier of a nestedhasOneworks.Team.clubis nullable in the fixture for these cases. 13 of the 20 tests fail with theAbstractHibernateQueryof 7.0.x: 12 with aQueryException, and the one for the requested left join with the rows of 7.0.x.CI passes with
run ci.