Repository navigation
Sort a criteria query by a property of an association - #17070
jdaugherty wants to merge 46 commits into
Conversation
Sorting a where query by a property of an association, such as sort: 'club.name', failed with a QueryException when the query also had criteria on that association. The criteria join the association under a generated alias, and the order was added with the association path, which Hibernate cannot resolve. The order now uses the alias of the join.
A sort by a path through more than one association, such as owner.employer.name, is still not supported.
This reverts commit b494caa.
A sort by a path that crosses more than one association, such as team.club.name, failed with a QueryException whether or not the where query joined the nested association, because order() split the path at its first dot only. The sort property is now qualified with the alias of the last association on its path: an association the query has already joined is reused, and one it has not joined yet is joined for the sort and registered like any other join. A sort by two properties of the same association no longer fails with "duplicate association path" either, since the sort join is registered instead of created anew for every order.
Since order() walks the whole sort path, a sort by the identifier of an association that follows another one on the path, such as team.club.id, joined that last association too. The join is an inner join unless fetch requests another type, so the sort left out the rows where the association is null. Before, only the first association was joined and Hibernate read club.id from the foreign key of team, which kept them. The identifier is sorted by the foreign key again when the entity before the association holds it. An association without such a foreign key, a hasOne or the inverse side of a one-to-one, is still joined, and so is the first association of a path, as it always has been. The spec also covers the join type of a sort join: an inner join by default, and a left join when fetch requests one. Team.club is nullable in the fixture for these cases. The docs describe the inner join, how to request a left join, and the identifier of a nested association.
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 apache#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 apache#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 apache#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 apache#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 apache#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 apache#16853.
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.
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 apache#16853.
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 apache#16853.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort through an alias stops at the first property and does not join the rest.
| */ | ||
| private void requestOrder(String propertyName, Function<String, Order> orderFactory) { | ||
| String[] tokens = propertyName.split("\\."); | ||
| if (tokens.length == 1 || datastore == null || aliasMap.containsValue(tokens[0]) || isAssociationIdentifier(tokens)) { |
There was a problem hiding this comment.
The query aliases team as t and sorts by t.club.name. That should join club and sort by its name. It throws, because the path is treated as already resolved once it starts with t. Join the rest of the path.
There was a problem hiding this comment.
Fixed in f2e1cc6. An order starting with an association alias now resolves the remaining path from that association and creates the missing joins. A direct alias property and a foreign-key identifier retain their existing handling.
The regression covers order("t.club.name", "desc") and Query.Order, with and without pagination. The association-sort specs pass in both compatibility-setting modes: 194 cases, 171 passed and 23 skipped. The module codeStyle check passes too.
Keep the count-projection and listener-order regressions, import RowCountProjection, and remove upgrade entries for calls that previously failed. Counts preserve joined rows rather than promising a distinct entity total.
Warn once at datastore startup for an explicitly false compatibility setting and cover unset, true and false. Rename the settings page, repair its links and list defaults separately for each release line. Carry the reviewed parent changes forward.
Document stored sorts using the requested fetch join type and repair the rendered list. Remove the one-caller association helper and unrelated import churn while merging the reviewed parent.
Load collections on paged requested-join paths separately, preserving complete contents. Retain each unmatched right-join row while deduplicating real entities. Exercise these results and cloned fetch replacements through public queries, and clarify the data-service limitation and changed results.
Select matching identifiers before bulk operations whose subqueries request joins. Correlate bidirectional collections through the owning property so tenant-filter parameters stay bound. Cover updates and deletes through nested criteria and tenant-scoped collection updates.
Reuse an existing alias with the requested join type regardless of declaration order. Keep paged collection fetches separate from limited SQL rows and document unpaged collection duplicates. Restore only the private join-lookup helpers needed by the criteria path.
Name the inner join added by a formerly ignored alias-prefixed sort and how to retain the old rows. Merge the reviewed criteria-join fixes and keep the existing join lookup private.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A left join the call asked for still drops a team with no players when the sort is by a player property.
| // the associations before a collection that the subquery joins are joined and fetched | ||
| JoinType lastJoinType = joinType == jakarta.persistence.criteria.JoinType.INNER ? JoinType.INNER_JOIN : | ||
| joinType == jakarta.persistence.criteria.JoinType.LEFT ? JoinType.LEFT_OUTER_JOIN : JoinType.RIGHT_OUTER_JOIN; | ||
| int joinedCount = unjoinedCollection < 0 ? tokens.length : unjoinedCollection; |
There was a problem hiding this comment.
Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) should include Playerless First Team. It is left out. The left join is not made, and the sort joins players as an inner join. Keep the left join.
matrei
left a comment
There was a problem hiding this comment.
Reviewed again at 6ff6caf. Points 1, 3 and 4 of my first review are fixed, and point 2 is below:
- "Results that change", the note and the skill entry say that a sort through an alias that goes on to another association, as in
sort: 't.club.name'withcreateAlias('team', 't'), leaves out the instances without that association unless the setting is enabled. They also say how to keep the rows. Withjoin('team.club', JoinType.LEFT), the 7 players stay, as with Hibernate 7. - The description says why
getJoinAliasandgetWholeAssociationPathare needed. I'm fine with that. - The pull request merges cleanly with 7.0.x and has
run ci, and CI passed with the tests.
My probes from the first review give the same results here as at e54321e, with the setting off and on, and the criteria probes of #17069 give what they give at #17069 (5ed82d5). The tests of grails-data-hibernate5-core pass here (1344 tests, 65 skipped), and the guide builds.
Needs a fix
1. James's new comment holds: a sort or an order by a collection doesn't use a left join that the criteria query requests for the collection.
Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { } |
7.0.x, #17069 and this head | the where query with the same arguments, here | #17079 |
|---|---|---|---|
| teams | Playerless First Team and Empty Team left out; Squad Team three times |
all 7 | all 7 |
The same goes for the call without max, for join('players', JoinType.LEFT) instead of the fetch argument, and for order('players.name'), which threw on 7.0.x and works here. The setting changes none of them.
For an association to a single instance it works: list(max: 10, sort: 'club.name', fetch: [club: JoinType.LEFT]) keeps the teams without a club, as at #17079. The description says that "an order uses the join and the join type that the criteria or the fetch argument request", and the note says that a left join that the query requests keeps the rows. For a collection, neither holds. The where query of the same stack keeps the teams, and #17079 does too, so after the merge-up the criteria query of Hibernate 5 and of Hibernate 7 return different rows.
Making the requested left join of a collection before the sort and the orders, so that they use it, as 429b6d5 does for an association to a single instance, would keep the teams. As for the other collections that a criteria query fetches (#17069), a team would then come once for each of its players.
2. Nothing tracks the Hibernate 7 counterpart. The description says that the fix for a map of sort properties with Hibernate 7 is a follow-up that should land before this part is released, but there's no issue or pull request for it. A map of sort properties in a criteria query still throws a ClassCastException with Hibernate 7, on 8.0.x and at #17079 (1cba001). An issue, named in the description next to the release ordering, would keep it from being missed when the stack is merged up.
Smaller points
- The description still names 4a6224d as the change to review. f2e1cc6 and 6ff6caf are part of it too.
- The imports of
WhereQueryWithAssociationSortSpecare reordered again here.
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 left join the call asked for is still undone by a sort on the static list.
| } else if (property instanceof Association) { | ||
| final Association<? extends Property> a = (Association<? extends Property>) property; | ||
| final Join join = queryRoot.join(sortHead); | ||
| final Join join = getOrCreateSortJoin(queryRoot, sortHead, !(a instanceof ToMany) && GrailsHibernateUtil.isLeftJoinAssociationSort(entity)); |
There was a problem hiding this comment.
Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]) should include Playerless First Team. It is left out. The left join is not made, and the sort joins players as an inner join. Keep the left join.
There was a problem hiding this comment.
This static-list collection-fetch case belongs to #17071. The public Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]) control was verified there at 98e75e9ab182 and keeps the team with no players. #17070 covers criteria orders and criteria sort arguments; the static-list implementation stays in #17071.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A left join the call asked for is still undone by a sort on the static list.
| } else if (property instanceof Association) { | ||
| final Association<? extends Property> a = (Association<? extends Property>) property; | ||
| final Join join = queryRoot.join(sortHead); | ||
| final Join join = getOrCreateSortJoin(queryRoot, sortHead, !(a instanceof ToMany) && GrailsHibernateUtil.isLeftJoinAssociationSort(entity)); |
There was a problem hiding this comment.
Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]) should include Playerless First Team. It is left out. The left join is not made, and the sort joins players as an inner join. Keep the left join.
✅ All tests passed ✅🏷️ Commit: 9dc26a4 Learn more about TestLens at testlens.app/docs. |
matrei
left a comment
There was a problem hiding this comment.
Third round, at 9dc26a4. Since my second review, 28e5534 fixed both of its points, and 9dc26a4 merged #17069's head. That merge brings #17067's new rule: a sort through a path below a requested JoinType.LEFT keeps the associations of the path outer. It also applies the rule to criteria queries. Apart from the criteria part, the tree is that of my own merge of 28e5534 and 1e09b41.
The points of my second review are fixed:
- A sort or an order by a collection keeps the left join that the criteria query requests.
Team.createCriteria().list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) { }now keepsPlayerless First TeamandEmpty Team, with the setting off and on. So do the call withoutmax,join('players', JoinType.LEFT)instead of thefetchargument, andorder('players.name').Squad Teamcomes once for each of its 3 players, andtotalCountcounts those rows. Hibernate 7 returns each team once. A criteria query sorted by a collection repeats its roots on 7.0.x too, assort: 'players.name'without a join type shows, and the note says that the rows per element stay. So I'm fine with that. On a paged query, the collection is loaded when accessed, with all its elements. - #17166 tracks the Hibernate 7 counterpart for a map of sort properties, and the description names it next to the release ordering.
The smaller points are settled too. The description says to review the changes relative to #17069, and the merge keeps one import of each class in WhereQueryWithAssociationSortSpec.
The new rule in criteria queries
I ran it with the domain of my earlier probes at this head and at 28e5534, on 7.0.x (28f27fe), and with Hibernate 7 on 8.0.x (99aedeb) and at #17079 (053255f):
| 7.0.x | This head, setting off and on | Hibernate 7 | |
|---|---|---|---|
Team.createCriteria().list(sort: 'players.contract.salary') { join('players.contract', JoinType.LEFT) }, also with order, with fetch instead of join, with max: 10 and with a sort map |
throws | all 7, Squad Team 3 times |
all 7, each once; the sort map throws (#17166) |
order('players.name') or order(Query.Order.asc('players.name')) with join('players.contract', JoinType.LEFT) |
throws, or 5 teams with Query.Order |
all 7 | all 7 |
A player without a team, in Player.createCriteria().list(sort: 'team.name') { join('team.club', JoinType.LEFT) } |
left out | kept | kept |
At 28e5534 the first row returned the 5 teams with players, Squad Team 3 times. order('team.name'), order('team.club.name') and join('team.players', JoinType.LEFT) with order('team.players.name') keep that player too, as at 28e5534. createAlias('players', 'p') before join('players.contract', JoinType.LEFT) keeps its inner join, and fetch: [players: 'select', 'players.contract': JoinType.LEFT] keeps all 7 teams, both as with Hibernate 7. On a page, as with max: 1 for Squad Team, the players aren't loaded with the query, and they hold all 3 when accessed.
The sort argument by a property of the collection itself
Team.createCriteria().list(sort: 'players.name') { join('players.contract', JoinType.LEFT) } still leaves out the two teams without players, with the setting off and on. So do fetch: ['players.contract': JoinType.LEFT] instead of the join, a sort map and max: 10. In the same query, order('players.name') and order(Query.Order.asc('players.name')) keep them. So do the where query Team.where { name ==~ '%' }.list(fetch: ['players.contract': JoinType.LEFT], sort: 'players.name') at #17067, and Hibernate 7 on 8.0.x and at #17079. On 7.0.x the sort argument also returns the 5 teams, so this isn't a regression. But the note says that the rule applies to the criteria sort, and order and sort now differ in the same query.
applyRequestedSortJoins makes the left join for the sort argument only when the sort is below a requested path, wholePath.startsWith(requested.getKey() + '.'). With sort: 'players.name' and a request for players.contract, the requested path is below the association of the sort instead, so the argument utilities join players with their inner join. I think that calling calculateOrderPropertyName in that case too, when requested.getKey() starts with the association path of the sort and a dot, fixes it, as isRequestedLeftSortJoin then picks the left join. A row with sort: 'players.name' for the path players.contract in a criteria #ordering keeps the left join of #path would cover it.
What I ran
- My probes of the first two rounds and of the count below: apart from the rows above, they give the same results as at 28e5534, with the setting off and on.
- The
grails-data-hibernate5-coretests: they pass at this head (1555 tests, 60 skipped), and the guide builds. This head has #17066's new page assertion, through #17067.
CI passed with the tests.
On James's comment of yesterday: Team.list(sort: 'players.name', fetch: [players: JoinType.LEFT]) is the static list, which #17071 changes, as jdaugherty replied. Here it returns what 7.0.x returns, without the two teams that have no players. At #17071 it returns all 7 teams, each once, as at #17079.
Optional
- A milestone for #17166. The description says #17166 should land on 8.0.x before this part is released. Putting it on
grails:8.0.1would keep it from being missed.
FYI, not for this part
The totalCount of a paged where query sorted by a collection counts the joined rows, not the instances that list returns:
Team.where { name ==~ '%' }.list(max: 10, sort: 'players.name', fetch: [players: JoinType.LEFT]) |
list |
totalCount |
|---|---|---|
| 7.0.x | 5 | 7 |
| #17062 to this head, with the setting off and on | 7 | 9 |
| Hibernate 7, on 8.0.x and at #17079 | 7 | 7 |
Without a join type it's 5 and 7 on every head of the stack, as on 7.0.x. #17067's new rule gives the same count: fetch: ['players.contract': JoinType.LEFT], sort: 'players.contract.salary' lists 7 teams and counts 9. It comes from 7.0.x and isn't made here, so it's for an issue of its own, which I can open.
Description
Part 10 of the split of #16853, as agreed there and in the dev@ thread Fixes that change results on patch and minor branches. Relates to #15589.
Stacked on #17069. Until that merges, this pull request also shows the commits below it. Review the changes introduced by this part, including its review fixes, relative to #17069.
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 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
#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.
Results that change
order('author.name')in a criteria query works instead of failing. Anorderthat is passed aQuery.Orderinside the criteria of an association sorts by the property of that association, not by the property of the queried class with the same name. A join made only for the order is an inner join, or a left join withgrails.gorm.leftJoinAssociationSort.orderout of the criteria of the association.The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry.
A formerly ignored sort such as a.publisher.name now joins the publisher. With the compatibility setting off it can leave out roots without that association, and changes their paged totalCount. Remove the sort to retain the former unsorted rows, or enable leftJoinAssociationSort to retain them while sorting. The guide and skill now state this.
getJoinAlias exposes the existing canonical join lookup across the cfg/query package boundary so ordering reuses the join created by criteria. getWholeAssociationPath is protected because HibernateCriteriaBuilder, in another package, uses it when registering aliases. The same-release criteria-join changes depend on that path identity.
The Hibernate 7 criteria sort-map counterpart is tracked by #17166, related to the existing sort-map report #14653. It should land on 8.0.x before this part is released across both modules, and remains outside the requested-join scope of #17079.
Verification
At 9dc26a4 the full Hibernate 5 core suite passes (1,560 cases, zero failures, 65 skipped). Root codeStyle, RAT (zero unknown licenses), dependency-version validation and the guide build passed. The reviewed parent fixes and release-branch conflict resolutions are included.
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