Repository navigation
Sort by an association with Hibernate 7 as with Hibernate 5, and keep the rows without it with leftJoinAssociationSort - #16863
jdaugherty wants to merge 37 commits into
Conversation
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.
jamesfredley
left a comment
There was a problem hiding this comment.
A sort by an ordinary association, including team.club.name and team.club.id, left-joins that association and keeps the rows whose association is null. A restriction that already inner-joins it still drops those rows. Not approving. A distinct projection ordered by the same association builds two joins, and databases reject the order. An alias created inside an association block is prefixed with that association, so the order no longer resolves. A sort through an embedded component, such as details.author.name, still inner-joins the association after the component and drops the rows whose association is null.
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.
jdaugherty
left a comment
There was a problem hiding this comment.
@jamesfredley, 6dc070d addresses review 5778258941.
- Distinct projection ordered by the same association: the order sorts by the expression that the projection selects, so the query has one join and runs again. This also covers
propertyandgroupProperty, a nested path, a where query and a criteria query with pagination arguments. Details are in the thread onJpaCriteriaQueryCreator. - Alias declared in an association block: the order is moved as the path that the alias stands for,
author.publisher.name, and sorts through the join of the alias. An order that names neither a property of the association nor an alias of the block stays in the block. Details are in the thread onCriteriaMethodInvoker. - Sort through an embedded component:
details.author.namenow joinsauthorwith a left join and keeps the rows whose author isnull, in a where query, a criteria query, a dynamic finder andlist, and thetotalCountof a paged list matches the list. A where query rendersleft join author a1_0 on a1_0.id=b1_0.details_author_id, andlistbuildsleft join e.details.author s0. A sort by a plain property of the component, such asdetails.isbn, still adds no join.
AssociationSortSpec has 29 cases now. 13 of the new ones fail on 7c2c241, as do the three new unit cases in ExpressionResolverSpec and HqlListQueryBuilderSpec. Section 90 of the upgrade notes covers the block alias and the component.
jamesfredley
left a comment
There was a problem hiding this comment.
Sorting by a selected association property, a single block alias, and through an embedded component now keeps the rows whose association is null. Not approving. Ordering inside a plain embedded block throws, and an order that names one of two aliases for the same collection can sort by the other alias.
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.
jdaugherty
left a comment
There was a problem hiding this comment.
@jamesfredley, 772b853 addresses review 5780261730.
- Order inside the block of an embedded component: the property is looked up on the entity of the association, so
details { order('isbn') }no longer throws and sorts by the embedded value. An order through an association inside the component,details { order('author.name') }, keeps the rows where that association isnull. Details are in its thread. - Order that names one of two aliases of a collection: the order is no longer rewritten to the association path. It keeps its block and is resolved against it, so
order('second.score')sorts by the join ofsecondandorder('first.score')by the join offirst. Details are in its thread. - Order by the path of a collection that has two aliases: found while fixing the previous one.
From.getJoins()is a set without an order, soorder('scores.score')sorted byfirstoutside a block and bysecondinside one. A sort by a path now reuses the first join that the query made for the association, which is the join that the path shares with its first alias.
AssociationSortSpec has 46 cases now. 8 of the 17 new ones fail on 6dc070d, as does the new unit case in ExpressionResolverSpec. Section 90 of the upgrade notes and the "Association Aliases" section of the Hibernate 7 criteria docs cover the block of an embedded component and the 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.
|
@jamesfredley, three commits follow 772b853, the one my reply to review 5780261730 describes. They come from a review of my own. The head is 3c54fc5, which also merges 8.0.x.
Section 90 of the upgrade notes covers the changes in results: a sort by a property of a collection, the instances without the association on the first page of a paged list, the requested inner join in counts and projections, and the orders of blocks. The PR description lists every change.
|
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. An order in the second of two blocks that share an association name sorts by the first block's join. An order declared inside a junction after a block order is no longer the primary sort. A distinct projection of an association ordered by that association's field still uses two joins.
|
@jdaugherty I took a look at 3c54fc5, focusing on the part the H2 specs cannot show: whether the SQL you now generate is accepted and correct on the real databases. I ran seven of the scenarios from
The distinct and group cases are the ones where PostgreSQL and Oracle reject an What I did not do: read all 2,977 lines line by line, and run Db2 (the image is amd64 only and I am on arm). CI on this head was still running when I looked, with nothing failing. The container spec is a throwaway, but it is small. If you want it as a guard I can send it over; it would live next to |
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.
|
Thanks for the round. I went through the main code (ExpressionResolver.resolveSort, AssociationOrders, HqlListQueryBuilder, JpaCriteriaQueryCreator) and compared the sort entry points on 8.0.x, on your head 3c54fc5 and on Hibernate 5. One thing needs a decision. list(sort: 'players.name') used to throw a PathException and now works. The entities are made distinct in memory after the SQL limit, so the pages repeat a team. With four teams and max: 2: page 1 is [Chelsea, ManU], page 2 is [Arsenal, Chelsea], page 3 is [Unattached]. Chelsea is on two pages and the pages hold 5 entries while totalCount is 4, which is the invariant this PR is about. Hibernate 5 returns one row per player (5 rows, total 5), so the two versions also differ. Either sorting through a collection should keep failing for a paged list, or the paging needs to happen on distinct entities, or the docs should say so. Which do you want? The rest matches what I expected: the null team is kept on first, last, where, finders and criteria, the paged total equals the rows returned for to-one paths, and an HQL findAll ignores the sort map exactly as on 8.0.x and Hibernate 5. |
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. An order that names an alias declared outside the block is dropped when that property is selected. Reusing a detached criteria as a subquery can throw because the block is registered on both queries. The second of two blocks now sorts by its own join, and an order inside a junction keeps its place. Threads PRRT_kwDOAAfRJ860KJxC and PRRT_kwDOAAfRJ860KJxJ resolved.
|
The consolidation branch, now #16891, merges this PR, and #16889 settled the question your six test cases ran into: blocks of one association with no alias share one join, and an alias after the first for a path has a join of its own, in another block as well. Your alias-per-block feature is unchanged and passes. The three features for unaliased blocks, which restricted the two blocks to round Say if you would rather keep them another way. |
8.0.x now keeps the joins of a query and of its association blocks in one map by their path, so two blocks of one association share a join. The four features that expected a join for each block are removed: such a query now applies the criteria of both blocks to the same join. The fetch mode join of list is a left join on 8.0.x, so the fetch joins that a sort reuses are written as left joins.
…nSort setting A sort by a property of an association changes which instances a query returns when it joins the association with a left join instead of an inner join. Following the dev@ discussion of fixes that change results, that is now behind grails.gorm.leftJoinAssociationSort, the setting that GORM for Hibernate 5 reads for the same change on 7.0.x. It is disabled by default, and 8.1 enables it by default. Without the setting, list, dynamic finders, criteria queries, where queries and detached criteria join an association that only a sort uses with an inner join. With it, they join it with a left join. The specifications of the sorts run with the setting off and on.
matrei
left a comment
There was a problem hiding this comment.
First round, at c175aca. The branch merges cleanly with 8.0.x at a509055, and CI passed.
I ran the same queries with both modules, with the setting off and on:
- 90 sorts through every query API;
- 25 calls of
findWhereandfindAllWhere; - 21 counts and page walks;
- 12 lists that fetch a bag.
Hibernate 7 ran at this head, on 8.0.x (a509055) and at #17079 (5cdfdac). Hibernate 5 ran on 7.0.x (ffd848b), and at #17070 (e431f96), #17071 (3128803), #17072 (02b0749) and #17073 (c5ae0d7).
A fetched bag holds its elements twice
A list sorted by one collection that fetches a bag fills the bag with each element once for each element of the sorted collection. The fixture has four teams:
Fullhas the membersaandband the trophiest1andt2;Membershas the memberc;Trophieshas the trophyt3;Emptyhas neither.
members is a Collection, so a bag, and trophies is a Set. These are the members of Full, the same with the setting off and on:
| 8.0.x | This head | #17079 | Hibernate 5 on 7.0.x | |
|---|---|---|---|---|
Team.list(sort: 'trophies.title', fetch: [members: 'join']), also with 'eager' and with max: 2 |
throws a PathException |
[a, a, b, b] |
[a, b] |
[a, b] |
Team.where { name ==~ '%' }.list(sort: 'trophies.title', fetch: [members: 'join']), also a detached criteria and findAllByNameLike |
[a, a, b, b] |
the same | [a, b] |
[a, a, b, b]; [a, b] at #17073 |
The where query, the detached criteria and the dynamic finder already do this on 8.0.x. The static list is new. This PR makes its sort by a collection work, which threw before, and that sort now returns wrong elements.
#17079 loads such a bag after the query and fixes all of these rows. I wouldn't merge this without it. Either take that part of #17079 into this PR for list, or merge the two together.
Differences from Hibernate 5 that the description doesn't list
"Agreement with Hibernate 5" says that this branch returns the rows that Hibernate 5 returns on 7.0.x:
- for every sort by an association to a single instance, in both modes of the setting;
- for a sort by a collection, except for an association after a collection with the setting on.
Of my 90 sorts, 68 give the same results as Hibernate 5 at #17070 with the setting off, and 73 with it on. Most of the rest are:
- ties of the sort;
- the type of exception for an order that doesn't resolve;
- a distinct projection ordered by a property of its association, which Hibernate 5 rejects.
These differ in their rows, with the setting off:
| Hibernate 5 on 7.0.x | Hibernate 5 at #17073 | This head | 8.0.x | |
|---|---|---|---|---|
Team.list(sort: 'club.id') |
the 5 teams with a club | the same | all 7 | all 7 |
Team.where { name ==~ '%' }.list(max: 10, sort: 'club.name', fetch: [club: 'join']), also with .join('club'), a detached criteria and findAllByNameLike |
5, totalCount 5 |
the same | all 7, totalCount 7 |
5, totalCount 7 |
Team.where { name ==~ '%' }.list(max: 10, sort: 'players.name', fetch: [players: 'join']) |
the 5 teams with players, totalCount 7 |
the same | all 7, totalCount 7 |
5, totalCount 7 |
Team.createCriteria().list { players { order('name') } } |
7 rows, Squad Team 3 times |
the same | the 5 teams with players, once each | the same as here |
- The id of an association: this head reads the foreign key and keeps the teams without a club, as 8.0.x does. A where query and
Player.list(sort: 'team.club.id')show the same difference. Hibernate 5 leaves them out with the setting off, which is #17160. Hibernate 7 is right here, but the section should name it. - A sort through the fetch join of an association: the description and the note say that it keeps the teams without a club, with or without the setting.
- I'm fine with that result. It's what the fetch asks for, and #17079 does the same for the criteria query.
- But it goes beyond the Hibernate 5 parts. With the setting off, it changes the rows of a where query on 8.0.x from 5 to 7.
- The note's "while GORM for Hibernate 5 keeps them only in a static
listunless the setting is enabled" holds from #17071 on. On 7.0.x, the staticlistof Hibernate 5 leaves them out too, even with the setting.
- A where query that fetches the collection it sorts by: here it sorts through the left join of the fetch. It keeps the teams without players with or without the setting, and lists each team once.
- Hibernate 5's static
listdoes that from #17071 on. Its where query leaves those teams out with the setting off, also at #17073. - The note says that a sort by a collection leaves out the instances whose collection is empty, and that a list that fetches a collection returns and counts each instance once. It could add that a list that fetches the collection it sorts by keeps them.
- Hibernate 5's static
- An order in the block of a collection: the rows are those of 8.0.x, since the block fetches the collection and Hibernate lists each team once. The description says that a criteria query returns an instance once for each element, as Hibernate 5 does. That holds for
order('players.name'), but not forplayers { order('name') }.
The setting in the guide
whereQueries.adocsays: "With thegrails.gorm.leftJoinAssociationSortsetting enabled, sorting does not change which rows a query returns". That holds for an association to a single instance. A sort by a collection, or by an association after one, still leaves rows out with the setting, as the upgrade note says further down.- The heading of the upgrade note, "A setting makes a sort by an association keep every instance with Hibernate 7", reads the same way. So does its "so that a sort no longer changes which instances a query returns". Until #17206, both could name the association to a single instance.
A junction that holds only a block
Team.createCriteria().list { or { club { order('name') } } } returns no team here. Hibernate 5 returns the 5 teams with a club, sorted by the club.
That's not new. On 8.0.x, an or without a criterion matches nothing: or { } and or { club { } } both return no team. Hibernate 5 matches every row for or { }, and every team with a club for or { club { } }. Now that a block order inside a junction is applied, this case is easier to reach. It doesn't need a change here, but an issue would keep track of it.
Fixed
-
codeconsole's review 6095121552: all three points hold at this head.
Team.where { name ==~ '%' }.list(max: 10, sort: 'players.name', fetch: [players: JoinType.INNER])lists and counts 5 teams. 8.0.x counts 7.sort: 'players.contract.salary', fetch: [players: 'join']lists and counts 5 teams with the setting off, and 7 with it on.sort: 'root.club.name', fetch: [club: 'join'], itscount(), andsort: 'root.club.id'keep the teams without a club, in the list and in its total.
-
Page walks: every page walk reaches every team that the same query returns without paging. I walked pages of 2 of:
- a where query, a criteria query,
listandcreateAlias, sorted by a collection; - a where query sorted by an association after a collection;
- a where query and
listthat fetch the collection they sort by; - a where query that fetches the club and sorts by it.
For the last one, 8.0.x has a
totalCountof 7, and its pages reach 5 teams. - a where query, a criteria query,
Smaller points
-
James's block order: I get what jdaugherty measured.
Team.withCriteria { club { order('name') } }returns the 5 teams with a club in both modules, in both modes of the setting, andclub(1) { order('name') }returns all 7. I agree with leaving it as it is. -
codeconsole's point 4 in review 6082994813: 8.0.x ignored both of these orders.
club { order('bogus') }now fails with anIllegalArgumentException.projections { distinct('name') }; club { order('name') }now fails at the database.
Hibernate 5 rejects both, and the note says so. I'm fine with that for 8.0.1.
-
join('club')with the setting on:Team.createCriteria().list { join('club'); order('club.name') }leaves out the teams without a club here, as on 8.0.x, becausejoin('club')fetches with an inner join. Hibernate 5 at #17070 keeps them. #17079 makes that fetch a left join. -
findWhereandfindAllWhere: with a sort, they find the same instances as without one, for a club,null, aStringfor anIntegerproperty and aGString. -
The paragraph on a block-local sort holds, in both modes, as with Hibernate 5 at #17070:
join('team.club', JoinType.LEFT), before or afterteam { order('club.name') }, keeps the player whose team has no club;JoinType.INNERleaves it out, also forclub.id.
What I ran
- Hibernate 7:
- Hibernate 5:
As a fix that changes a result, this needs a second approval under #17061.
|
A follow-up to my review: the
Only this PR and #17010 together make |
…le instance The guide, the upgrade note and the skill entry said that with grails.gorm.leftJoinAssociationSort a sort no longer changes which instances a query returns. That holds for an association to a single instance; a sort by a collection, or by an association after one, still joins with an inner join with or without the setting. The note also says that a list that fetches the collection it sorts by keeps the instances whose collection is empty, that an order in the block of a collection returns each instance once, as on 8.0.0, and that GORM for Hibernate 5 leaves out the instances without a fetched association while the setting is disabled, also in a static list.
jdaugherty
left a comment
There was a problem hiding this comment.
@matrei, review 6098316358:
- The fetched bag: this pull request is merged together with #17079, which loads such a bag after the query, so the static
listholds[a, b], as you measured at 5cdfdac. The description says so and lists the staticlistwith a bag among the differences from Hibernate 5 that this pull request has on its own. - Differences from Hibernate 5: "Agreement with Hibernate 5" now names the sort by
club.id(#17160), the sort through the fetch of an association or of the collection that the query sorts by, and the order in the block of a collection. In bd990f6 the upgrade note says that GORM for Hibernate 5 leaves out the instances without a fetched association while the setting is disabled, in place of "keeps them only in a staticlist". It also says that a list that fetches the collection it sorts by keeps the instances whose collection is empty, and that an order in the block of a collection returns each instance once, as on 8.0.0. The skill entry says the same. 'an order inside the block of a collection lists each instance once, as the block fetches the collection' inAssociationSortSpeccovers the last, with the setting off and on. - The setting in the guide: the sentence in
whereQueries.adoc, the heading and first paragraph of the upgrade note, the skill entry and the description now say that the setting is for a sort by an association to a single instance, and that a sort by a collection, or by an association after one, joins with an inner join with or without it, until #17206. - A junction that holds only a block: #17208.
James's two threads report the block order of PRRT_kwDOAAfRJ86870p7 again. It stays as it is, as with Hibernate 5; the replies say why and which spec checks it.
| @Override | ||
| D findWhere(Map queryMap, Map args) { | ||
| if (!queryMap) return null | ||
| if (requestsSort(args)) { |
There was a problem hiding this comment.
As in PRRT_kwDOAAfRJ86870p7 and the threads before it: the club block is what joins club, and a block joins its association with an inner join unless it asks for another one. The setting only decides the join that a sort makes by itself. Team.createCriteria().list { club { order('name') } } is the query that withCriteria runs, and Hibernate 5 on 7.0.x returns the same rows for it, without the team that has no club. "an order inside an association block of a criteria query sorts by the property of the association" in AssociationSortSpec checks it on c175aca, with the setting off and, through AssociationSortLeftJoinSpec, on. To keep the team without a club, give the block a left join, club(1) { order('name') }, or sort outside the block with order('club.name').
| * through the association, as with Hibernate 5, and reuses the join of the block. | ||
| */ | ||
| private static void moveOrdersOutOf(DetachedAssociationCriteria<?> block, HibernateQuery hibernateQuery) { | ||
| String associationPath = block.getAssociationPath(); |
There was a problem hiding this comment.
This is the call of PRRT_kwDOAAfRJ86870p7, answered there with Hibernate 5 measured on 7.0.x, and of PRRT_kwDOAAfRJ868_qts: the block joins club with an inner join, as with Hibernate 5, and the setting only decides the join that a sort makes by itself. Nothing in this pull request has changed that since; club(1) { order('name') } or order('club.name') keeps the team without a club.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A find that asks to be read only, and also sorts, can still be written.
This comment has been minimized.
This comment has been minimized.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16863 +/- ##
================================================
+ Coverage 0 62.9127% +62.9127%
- Complexity 0 27815 +27815
================================================
Files 0 2252 +2252
Lines 0 112157 +112157
Branches 0 20610 +20610
================================================
+ Hits 0 70561 +70561
- Misses 0 32185 +32185
- Partials 0 9411 +9411 🚀 New features to boost your workflow:
|
findWhere and findAllWhere with a sort run as a criteria query, which did not read the readOnly argument, so the instances they returned were written back on flush. The query now applies it, as the HQL query of an unsorted call does.
matrei
left a comment
There was a problem hiding this comment.
Second round, at d61a1e0:
- bd990f6 changes the guide, the upgrade note, the skill and
AssociationSortSpec, as my first review asked. - d61a1e0 keeps
findWhereandfindAllWhereread-only with a sort, which James's review of 15:45 asked for.
The branch merges cleanly with 8.0.x at a509055. AssociationSortSpec passes at this head, with both new features (152 tests, 13 skipped). CI is still running.
Fixed
-
The fetched bag: the description says that this pull request is merged together with #17079, which loads such a bag after the query. It also lists the static
listwith a bag among the differences that this pull request has on its own. At #17079 the staticlistholds[a, b]. -
The differences from Hibernate 5: "Agreement with Hibernate 5" names the four that I listed:
- the sort by
club.id(#17160); - the sort through a fetch;
- a list that fetches the collection it sorts by;
- the order in the block of a collection.
The upgrade note and the skill entry now describe the last three. The new feature of
AssociationSortSpeccovers the order in the block of a collection. - the sort by
-
The setting in the guide:
whereQueries.adoc, the heading and first paragraph of the upgrade note, the skill entry and the description say that the setting is for a sort by an association to a single instance. -
readOnlywith a sort: with the teamsMUandArsenal, I readMUfrom the query, changed itsrank, flushed, cleared the session and read it again:8.0.x bd990f6 This head Hibernate 5 on 7.0.x Team.findWhere([name: 'MU'], [sort: 'rank', readOnly: true]), also withorder: 'desc'not written written not written not written Team.findAllWhere([name: 'MU'], [sort: 'rank', readOnly: true])not written written not written not written
Smaller points
- #17208 is the same case as #17174, which asks what an
orwithout a criterion should mean. #17010 makes Hibernate 7 return what Hibernate 5 returns there, as my comment of 14:52 says. #17208 could be closed for #17174, and the description could name #17174 and #17010. - Other queries that ignore
readOnly: a where query, and a dynamic finder with a sort, don't applyreadOnlyin either module, on 8.0.x too. That doesn't come from this pull request.
What I ran
AssociationSortSpec: at this head.- The
readOnlyrows: at this head, at bd990f6, on 8.0.x (a509055), and with Hibernate 5 on 7.0.x (ffd848b). - The rows of my first review: I didn't rerun them. The code changed since c175aca only in
findWhereandfindAllWhere.
As a fix that changes a result, this needs a second approval under #17061.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort in a block that has no other restriction still drops a team with no club.
| // the orders of the block sort the query, in the place they were declared in | ||
| moveOrdersOutOf(associationCriteria, hibernateQuery); | ||
| } | ||
| hibernateQuery.add((Query.Criterion) associationCriteria); |
There was a problem hiding this comment.
The setting that keeps a row with no association is on. Team.withCriteria { club { order('name') } } should include Unattached First Team. It is left out, because this adds the block as a restriction after moving the order out. Keep the team.
There was a problem hiding this comment.
As in PRRT_kwDOAAfRJ86870p7 and the threads after it: the club block joins club with an inner join, as with Hibernate 5, and the setting only decides the join that a sort makes by itself. matrei measured the same in both modules, in both modes of the setting, in review 6098316358. club(1) { order('name') } or order('club.name') keeps the team without a club.
codeconsole
left a comment
There was a problem hiding this comment.
Five defects need to be fixed before merging (details inline):
- Multi-order collection sorts under
leftJoinAssociationSort = true(e.g.order('players.name')followed byorder('players.contract.salary')) left-joincontractincount()/totalCountwhilelist()implicitly inner-joins it, inflating the count. HibernateQuery.clone()copiesfetchJoinPathseven for projection queries that did not fetch anything, causingtotalCounton paged projection queries withfetch: [assoc: 'join']and a sort to overcount or switch tocountDistinct.JpaQueryContext.isColumnOfRootreturnstruefor unjoined to-one association paths (embedded component associations likedetails.author.nameand{alias}.club.name), solistDistinctkeeps SQLDISTINCTand fails at the database.- Sorted
findWhere/findAllWheredropflushMode,fetchSize, andtimeout(onlyreadOnlyis forwarded). JpaCriteriaQueryCreator.isSelecteddoes not strip a leadingroot.prefix, creating a duplicate join ondistinct('club.name')+order('root.club.name').
Simpler/clearer: drop the unused .withConnection(getQualifier()) in HibernateGormStaticApi.whereCriteria, and consider collapsing sortJoins/collectionSortJoins/afterCollectionSortJoins in HqlListQueryBuilder into one map holding alias and join-type metadata.
| Path<?> parent = path.getParentPath(); | ||
| while (parent != null && parent != getRoot()) { | ||
| // the path of a collection is joined when it is read, although it is no join of the query | ||
| if (parent instanceof Join<?, ?> || parent.getModel() instanceof Attribute<?, ?> attribute && attribute.isCollection()) { |
There was a problem hiding this comment.
isColumnOfRoot treats any non-collection Path segment that is not a Join as a column of the root table. When resolveSort falls back to a plain Path that crosses a to-one association — such as an association inside an embedded component (listDistinct { order('details.author.name') }) or a {alias}-prefixed association (listDistinct { order('{alias}.club.name') }) — parent is a Path with Attribute.isAssociation() == true that is neither a Join nor a collection. isColumnOfRoot returns true, distinctInMemory stays false, and H2/PostgreSQL reject the SELECT DISTINCT ... ORDER BY query.
Fix: pass endsWithForeignKey into isColumnOfRoot and return false for any parent with parent.getModel() instanceof Attribute<?, ?> attr && attr.isAssociation() except the immediate parent of a foreign-key column (endsWithForeignKey && parent == path.getParentPath()).
There was a problem hiding this comment.
This is the same on 8.0.x (42951ae): listDistinct { order('details.author.name') } and listDistinct { order('{alias}.club.name') } fail at the database there too, so this pull request leaves them as they are. A sort through an embedded component and a sort by the root alias are outside it, as its description says. listDistinct { order('club.name') }, which failed on 8.0.x, works here.
…of a sorted findWhere A count joins the rest of a sort path with inner joins after a collection that an earlier order of the count joined, as the list reads it, so two orders through the players count the rows of the list with leftJoinAssociationSort. The count of a page that selects properties no longer joins the associations the query asks to fetch, which its list does not fetch. An order with the root. prefix sorts a distinct query by what it selects. A sorted findWhere or findAllWhere applies flushMode, fetchSize and timeout as an unsorted call does.
…nto requested join types The count of a page that selects properties also leaves out the fetches of the query here, since such a list fetches nothing.
jdaugherty
left a comment
There was a problem hiding this comment.
@codeconsole, review 6100460995: #1, #2, #4 and #5 are fixed in ae85725, each with a feature in AssociationSortSpec that failed before the fix, in the mode you describe. I ran each case on 8.0.x (42951ae) too. #1 and #5 are new with this pull request, with the setting on. #4 came with the sorted findWhere. #2 gave the same totals on 8.0.x, but this pull request says that a total counts the rows that its list pages through, also for a query with projections, so it is fixed here. #3 fails the same way on 8.0.x, as the reply says. whereCriteria no longer calls withConnection(getQualifier()), which nothing read once the sorted findWhere ran its criteria itself. The three join maps of HqlListQueryBuilder stay as they are: merging them is a refactor that this pull request does not need.
James's review 6099657519 reports the block order of PRRT_kwDOAAfRJ86870p7 again. It stays as it is, as with Hibernate 5; the reply is in the thread.
| // the orders of the block sort the query, in the place they were declared in | ||
| moveOrdersOutOf(associationCriteria, hibernateQuery); | ||
| } | ||
| hibernateQuery.add((Query.Criterion) associationCriteria); |
There was a problem hiding this comment.
As in PRRT_kwDOAAfRJ86870p7 and the threads after it: the club block joins club with an inner join, as with Hibernate 5, and the setting only decides the join that a sort makes by itself. matrei measured the same in both modules, in both modes of the setting, in review 6098316358. club(1) { order('name') } or order('club.name') keeps the team without a club.
| Path<?> parent = path.getParentPath(); | ||
| while (parent != null && parent != getRoot()) { | ||
| // the path of a collection is joined when it is read, although it is no join of the query | ||
| if (parent instanceof Join<?, ?> || parent.getModel() instanceof Attribute<?, ?> attribute && attribute.isCollection()) { |
There was a problem hiding this comment.
This is the same on 8.0.x (42951ae): listDistinct { order('details.author.name') } and listDistinct { order('{alias}.club.name') } fail at the database there too, so this pull request leaves them as they are. A sort through an embedded component and a sort by the root alias are outside it, as its description says. listDistinct { order('club.name') }, which failed on 8.0.x, works here.
✅ All tests passed ✅🏷️ Commit: ae85725 Learn more about TestLens at testlens.app/docs. |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort in a block that has no other restriction still drops a team with no club.
| // the orders of the block sort the query, in the place they were declared in | ||
| moveOrdersOutOf(associationCriteria, hibernateQuery); | ||
| } | ||
| hibernateQuery.add((Query.Criterion) associationCriteria); |
There was a problem hiding this comment.
The setting that keeps a row with no association is on. A list that sorts club by name inside a block should include Unattached First Team. It is left out, because this adds the block as a restriction after moving the order out. Keep the team.
codeconsole
left a comment
There was a problem hiding this comment.
One count bug and one inaccurate upgrade-note statement need to be fixed before merging (plus two minor cleanups). Note also that coordination with #17079 remains necessary for static list sorting by a collection while fetching a bag.
| return getPath(from, String.join(".", Arrays.copyOfRange(tokens, i, tokens.length))); | ||
| } | ||
| // the joins after such a collection are made by the sort, as the path of the list reads them | ||
| From<?, ?> join = afterCollection ? null : queryJoin(from, tokens[i], associationPath); |
There was a problem hiding this comment.
When count() / paged totalCount (joinCollections == true) has multiple orders traversing the same association past a sort-joined collection — e.g. sort: ['owners.scores.score': 'asc', 'owners.scores.round': 'asc'] or order('players.contract.salary'); order('players.contract.version') — the second order reuses the first collection join, sets afterCollection = true on line 211, and then skips existingJoin here on the next segment. That creates a second INNER JOIN on scores (or contract), which for a nested collection produces a Cartesian product and inflates count()/totalCount in both leftJoinAssociationSort modes (e.g. 12 instead of 6 on AssociationSortSpec's league fixture).
Fix: check existingJoin(from, tokens[i]) when afterCollection is true instead of returning null:
From<?, ?> join = afterCollection ? existingJoin(from, tokens[i]) : queryJoin(from, tokens[i], associationPath);Every join on a sortCollectionJoins join (or its descendants) was created with JoinType.INNER by an earlier order in this count, so this still ignores planned/implicit join types while reusing joins created by earlier orders. Please add regression tests in AssociationSortSpec and ExpressionResolverSpec.
| * A sort by a property of a collection, such as `sort: 'tags.name'`, works as it does with Hibernate 5. It joins the collection with an inner join, with or without the setting, and leaves out the instances whose collection is empty. `list` and a criteria query return an instance once for each element of its collection, as with Hibernate 5. A where query, a detached criteria and a dynamic finder return an instance once from the rows that they read; they returned it once for each element. `max` and `offset` page through the rows of the elements, and `count` and the `totalCount` of a paged list count those rows, so a page of a where query can hold fewer instances than its total counts: for two authors with two books each, `Author.where { name ==~ '%' }.list(max: 10, sort: 'books.title')` returns the two authors and a `totalCount` of 4. An association after the collection on the sort path, as in `sort: 'books.publisher.name'`, is joined with an inner join as well, with or without the setting, so a book without a publisher has no row; with Hibernate 5, the setting keeps its row. A list that fetches a collection, the one it sorts by or another one, returns and counts each instance once. A list that fetches the collection it sorts by with `'join'` or `'eager'`, as in `Author.where { name ==~ '%' }.list(sort: 'books.title', fetch: [books: 'join'])`, sorts through the left join of that fetch, so it also returns the instances whose collection is empty, with or without the setting. For paging without repeated instances, sort by a property of the queried class or of a to-one association instead. `Book.list(sort: 'tags.name')` failed with a `PathException` and now works. | ||
| * An `order` inside an association block of a criteria query, such as `author { order('name') }`, now sorts the query by that property of the association, through the join of the block, as with Hibernate 5. It was ignored. This also applies inside `and`, `or` and `not`, and the order keeps its place among the orders of the query. The block of a collection, as in `books { order('title') }`, fetches the collection, so such a query returns each instance once, as on 8.0.0, where Hibernate 5 returns it once for each element. An order in a block that names no property of the association now fails with an `IllegalArgumentException`, as it does outside a block. In a query that selects distinct values of a property, grouped values or aggregates, such as a query with a `distinct`, `groupProperty` or `max` projection, most databases reject an order by a value that the query does not select, so such a query with an order in a block now fails at the database, as with Hibernate 5. Both orders were ignored. Remove such an order to get the previous result. | ||
| * A query that selects a property of an association with `property`, `distinct` or `groupProperty` and sorts by the same property is ordered by the selected value, as before, and so still returns only the instances that have the association. The same holds for a query that selects the association itself and sorts by one of its properties, such as `distinct('author')` with `order('author.name')`. | ||
| * The criteria builder now evaluates the closure of `and`, `or` and `not` itself, as it evaluates every other closure of a criteria query, so an association block inside one of them is the same as a block outside it. A join type given to such a block, as in `or { author(1) { ... } }` for a left join, was ignored and is now applied. To keep the inner join, leave the join type out. The association of such a block is now also fetched with the query, as it is for a block outside a junction, which does not change the instances that the query returns. |
There was a problem hiding this comment.
"which does not change the instances that the query returns" is inaccurate in two cases now that CriteriaMethodInvoker evaluates junction closures:
- A collection block inside
and/or/not(e.g.or { players { like('name', '%') } }) now callshibernateQuery.join(..., JoinType.INNER), adding the collection tofetchJoinPathsand causingapplyRequestedJoinstoroot.fetch(...)it. Hibernate 7 deduplicates roots on a collection fetch, so each root is now returned once instead of once per matching element as on 8.0.0. - A self-referential association block inside a junction now hits
CriteriaMethodInvoker'sassociationClass.equals(oldTargetClass)branch and defaults toJoinType.LEFTinstead ofJoinType.INNER, retaining rows whose self-association isnull.
Please update this sentence to reflect those changes.
| * A sort path without the {@code root.} prefix, which names the queried class, as the sort of a list reads it. | ||
| */ | ||
| private static String withoutRootPrefix(String propertyName) { | ||
| return propertyName.startsWith("root.") ? propertyName.substring(5) : propertyName; |
There was a problem hiding this comment.
Optional cleanup: unlike ExpressionResolver.resolveSort (line 173), withoutRootPrefix does not guard against propertyName == null, so an order with a null property throws NullPointerException instead of IllegalArgumentException("Invalid sort property").
|
|
||
| def "test a sort path that ends with a foreign key is not joined for it"() { | ||
| given: | ||
| def root = Mock(From) |
There was a problem hiding this comment.
Optional cleanup: root and context here are unused (lines 339–340 create sqmRoot and sqmContext instead).
Description
Hibernate 7 counterpart of the Hibernate 5 association-sort parts on 7.0.x: #16853, #17062, #17064 and #17065, and the approved #17070. It matches what those parts do with Hibernate 5 and nothing beyond them.
With GORM for Hibernate 7, a sort by a property of an association, such as
Team.list(sort: 'club.name'), read the property through its path, which Hibernate joins with an implicit inner join. The sort left out the instances whose association isnull, and thetotalCountof a paged list still counted them, so a page of 3 teams had atotalCountof 4. A sort byclub.idkept them, because Hibernate reads the id from the foreign key.What changes:
countand thetotalCountof a paged list keep those joins, without theORDER BY. A total therefore counts the rows that the list pages through. This applies to where queries, detached criteria, dynamic finders, criteria queries,list, andfindWhere/findAllWhere, which now apply theirsortargument as with Hibernate 5. A query with projections is counted with the same joins.grails.gorm.leftJoinAssociationSort(the setting that Add a setting that keeps the rows without an association when sorting by it #17065 adds for Hibernate 5 on 7.0.x, off by default on 8.0.x, on from 8.1 with GORM: enable leftJoinAssociationSort by default in Grails 8.1 #17164, removed in 9 with GORM: remove the leftJoinAssociationSort compatibility setting in Grails 9 #17165), a sort by an association to a single instance joins it with a left join, so it keeps the instances whose association isnull, and the total counts them. The setting does not change a sort by a collection (below); keeping the instances whose collection is empty with the setting, as Sort by and join a collection without changing what a query fetches #17072 does for Hibernate 5, is Hibernate 7: with leftJoinAssociationSort, keep the instances whose collection is empty in a sort by the collection, as #17072 does for Hibernate 5 #17206.sort: 'scores.score', works as with Hibernate 5: the collection is joined with an inner join, with or without the setting, so the instances whose collection is empty are left out.maxandoffsetpage through the rows of the elements, andcountand thetotalCountcount those rows; a list that fetches the collection it sorts by returns and counts each instance once, and since it sorts through the left join of that fetch, it also returns the instances whose collection is empty, with or without the setting.listand a criteria query with an order by the path, such asorder('scores.score'), return an instance once for each element, as Hibernate 5 does. An order in the block of the collection, as inscores { order('score') }, returns each instance once, as on 8.0.0, because the block fetches the collection; Hibernate 5 returns it once for each element. A where query, a detached criteria and a dynamic finder return an instance once from the rows that they read.Book.list(sort: 'tags.name')failed with aPathExceptionand now works. An association after a collection on a sort path, as insort: 'players.contract.salary', is joined with an inner join too, in both modes, in the list and in its count; with the setting on, Hibernate 5 joins that association with a left join and keeps a row for an element whose association isnull, which Hibernate 7 cannot do without listing each instance once.'join'or'eager', or withjoin('author')on a where query or a detached criteria, uses the left join of the fetch, with or without the setting, so it returns the instances without the association, as a staticlistwith such a fetch already did on 8.0.x, and the count and thetotalCountof a page count them too. Hibernate 5 on 7.0.x leaves them out while the setting is disabled, also in a staticlist, so this goes beyond its parts there; Apply a join type in the fetch argument of list and the example queries #17071 makes its staticlistkeep them. RequestJoinType.INNERfor the fetch, or with the setting off leave the fetch out, to leave them out as before.ExpressionResolver.resolveSort, which reuses a join that the query already has for the association, or a join of the type that the query requests for it, and otherwise joins it as described above.JpaCriteriaQueryCreatorassigns the orders after the criteria, so that an order reuses the join of the criteria, which is an inner join by default.HqlListQueryBuilderjoins the associations thatlistsorts through and sorts by the alias of that join. A count keeps the joins of the orders without theORDER BY:HibernateQuery.clearOrders()keeps the orders it clears for that, as Hibernate 5 keeps the alias that an order joined, so the sharedgrails.gorm.PagedResultListis unchanged.orderinside an association block of a criteria query, such asclub { order('name') }, was ignored. It was added to the criteria of the block, and only the orders of the root criteria reach the query. The builder now moves it to the enclosing criteria when the block ends, as an order by the path through the association,club.name, which sorts through the join of the block, as with Hibernate 5. Orders in the blocks of a detached criteria built in another way, and in the block of an embedded component, are still ignored, as with Hibernate 5 and on 8.0.0.and,orandnotitself, as it evaluates every other closure of a criteria query and as the Hibernate 5 builder does. The detached criteria evaluated it, so an association block inside a junction was not a block of the builder, and its orders stayed in the block. A block inside a junction is now the same as a block outside one: its orders keep the place they were declared in, a join type given to it, as inor { club(1) { ... } }, is applied where it was ignored, and its association is fetched with the query.listDistinctselects distinct entities, and SQL rejects an order of a distinct query by a column that is not in its select list.listDistinct { order('club.name') }failed for that reason, andlistDistinct { club { order('name') } }would have. When a distinct list is ordered by a value that is not a column of the entity, the query is now built without the SQL keyword and the entities are made distinct once they are read, as Hibernate 5 did for a distinct list.order('club.bogus'), failed with a bareAssertionErrorfrom Hibernate. It is now rejected with theIllegalArgumentExceptionthatlistthrows for an invalid sort property, as Hibernate 5 rejects it with aQueryException. An order of a block that does not resolve is rejected in the same way; it was left out. A query with adistinct,groupPropertyor aggregate projection that a block orders by a value it does not select reaches the database, which rejects it on most databases, as with Hibernate 5.property,distinctorgroupPropertysorts by the expression of the projection and not through a join of its own. A distinct or grouped query can only be ordered by what it selects, soprojections { distinct('club.name') }withorder('club.name')keeps its one join. The same holds when the query selects the association that the property belongs to, asprojections { distinct('club') }withorder('club.name')does.fetch: [club: 'join'], sort: 'club.name'joins the club once.listgives the fetch join an alias and sorts through it.HqlListQueryBuilderresolves a sort path in one walk, which validates the path against the mapping and decides where each part is read from. It walked the path once to validate it and once more for the joins.club.id, is read from the foreign key without a join, as before this PR, in criteria queries and inlist. The mapping of the property decides, because the JPA metamodel reports ahasOneassociation as a many-to-one too, although its key is in the other table. A sort bycontract.idthrough ahasOnetherefore joins the association with a left join.Fixes next to the sort
This came up while reviewing the sort and is fixed here, as #17067 fixes it for Hibernate 5, since it stood in the way of a sort that the PR documents:
join('club', JoinType.INNER)orfetch: [club: JoinType.INNER], was only applied through the fetch join of a full-entity select.count(), thetotalCountof a paged list and a query with projections had no join and counted the instances without the association, so a paged list returned 3 teams with atotalCountof 4. The association is now joined with a plain join in those queries. A requested inner join of a collection is not changed.Agreement with Hibernate 5
This branch returns the rows that Hibernate 5 returns on 7.0.x for a sort by an association to a single instance and for a sort by a collection, in both modes of the setting, apart from these:
Team.list(sort: 'club.id'), reads the foreign key and keeps the instances without the association, as on 8.0.0. Hibernate 5 leaves them out with the setting off, which is GORM for Hibernate 5: a sort by the id of an association leaves out the instances whose association is null #17160.players { order('name') }, returns each instance once, as on 8.0.0, where Hibernate 5 returns it once for each element.listthat sorts by one collection and fetches a bag, asTeam.list(sort: 'trophies.title', fetch: [members: 'join'])does withmembersaCollection, holds each element of the bag once for each element of the sorted collection; on 8.0.0 that sort threw aPathException. A where query, a detached criteria and a dynamic finder already did that on 8.0.0. Apply a requested join type with Hibernate 7 #17079, which is merged together with this pull request, loads such a bag after the query.Where the two still differ outside this PR's scope, the difference is tracked separately:
findAllwith an example that sets no property returnsnullhere (#17169), and anorwithout a criterion, alsoor { club { order('name') } }, matches no row, as on 8.0.0 (#17208). An association block always joins its association, by default with an inner join, in both modules: with the setting on,Team.withCriteria { club { order('name') } }leaves out a team without a club with Hibernate 5 as well, andclub(1) { order('name') }ororder('club.name')keeps it.Not in this PR
Documentation
The "Query Aliases and Sorting" section of the Hibernate 7 where-query docs and the "Association Aliases" section of the criteria docs describe sorting by an association and an
orderinside an association block. The Grails 8.0.1 section of the upgrade notes and the upgrade skill describe the setting, which rows and totals change in each mode, a sort by a collection, and how to get the previous results.Tests
AssociationSortSpec,WhereQueryWithAssociationSortSpecand their*LeftJoinSpecsubclasses, which run every case with the setting on, cover the sorts through each query API, the totals and counts, sorts by a collection and block orders.ExpressionResolverSpec,HqlListQueryBuilderSpec,JpaQueryContextSpecandCriteriaMethodInvokerSpeccover the joins that a sort makes or reuses and the orders that come out of association blocks.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