Repository navigation
Apply a join type in the fetch argument of list and the example queries - #17071
jdaugherty wants to merge 26 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.
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.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A left join in the fetch argument is undone by a sort of that association.
| aliasMap.put(associationPath, alias); | ||
| String joinPath = parentAlias != null ? parentAlias + '.' + tokens[i] : associationPath; | ||
| criteria.createAlias(joinPath, alias, property instanceof ToMany || !GrailsHibernateUtil.isLeftJoinAssociationSort(property.getOwner()) ? | ||
| org.hibernate.sql.JoinType.INNER_JOIN : org.hibernate.sql.JoinType.LEFT_OUTER_JOIN); |
There was a problem hiding this comment.
The list asks to fetch club with a left join and then sorts by club.name. A team with no club should stay. It is dropped, because the sort joins club as an inner join. Use the left join the call asked for.
There was a problem hiding this comment.
The fix belongs to the requested criteria joins in #17069 and is now carried into this branch by b42dc27. An explicit LEFT join is created before deferred orders are applied, so order("club.name") reuses it even when leftJoinAssociationSort is off.
The stacked tests now cover a LEFT fetch argument followed by an order, and a LEFT join requested after the order, in both setting modes. The 20 focused criteria-order/LEFT-join cases pass. The complete Hibernate 5 core suite on the combined stack also passes: 1,636 cases, 159 skipped, with codeStyle clean. No separate static-list behavior change was added to this PR for this finding.
matrei
left a comment
There was a problem hiding this comment.
Reviewed at b42dc27 (base 7.0.x): 66a5e5b and the merge of #17070's head, which merges without a conflict. I probed list, a paged list, findWhere, findAllWhere, and find and findAll with an example, with a join type and with 'join' and 'eager' in the fetch argument, also with a sort, for a to-one association, a nested path, a collection and a path through one:
- at this head, at #17070 (e54321e), on 7.0.x (aee4c04) and at the stack top (16bd465), with the setting off and on;
- with Hibernate 7 on 8.0.x (0518f48) and at #17079 (6de9334).
The setting changes none of these results, and #17070 returns what 7.0.x returns. This head returns what #17079 returns, except for point 2 and notes 5 and 7:
| 7.0.x and #17070 | This head | Hibernate 7 on 8.0.x | #17079 | |
|---|---|---|---|---|
Team.list(fetch: [club: 'join']), also 'eager', and with sort: 'club.name' |
5 teams, the club not fetched | 7, the club fetched | 7 | 7 |
Team.list(max: 2, fetch: [club: 'join']).totalCount |
5 | 7 | 7 | 7 |
Team.list(fetch: [players: 'join']) |
7 rows: the team with three players three times, without the two teams that have none | 7 teams | 7 | 7 |
Team.list(fetch: [club: JoinType.INNER]) |
7 | 5 | 7 | 5 |
Team.list(fetch: ['players.contract': JoinType.INNER]), also the totalCount of max: 2 |
7 | 5 | 7 | 5 |
Player.list(fetch: ['team.club': JoinType.INNER]) |
7 players | 6 | 7 | 6 |
Team.list(sort: 'club.name', fetch: [club: JoinType.LEFT]) |
5 | 7 | 5 | 7 |
findAllWhere([name: 'Unattached First Team'], [fetch: [club: JoinType.INNER]]), also findWhere, and find and findAll with an example |
the team | nothing | the team | nothing |
So I agree that this needs no setting, by #17061. For 'join', Hibernate 7 on 8.0.x returns the new rows since #16898. For a join type, the old result ignores the join type that the call requests.
This also settles what I left open in note 6 on #17065. With the setting off, Team.list(sort: 'club.name', fetch: [club: 'join']) returns 7 teams at the stack top because the fetch is now a left join, and the sort uses it, as at #17079.
Needs a fix
1. A paged list that fetches a collection now pages in memory. Team.list(max: 2, fetch: [players: 'join']), and the same with JoinType.LEFT, JoinType.INNER or 'players.contract', now return the right page, with the collections complete. On 7.0.x, max: 2, offset: 1 returned the team with three players twice, and the collection wasn't fetched. But Hibernate 5 now logs HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!. It selects every row of the query and pages in memory, where 7.0.x limited the rows in the database and logged no such warning. For a large table, a paged list with a collection fetch now loads the whole table. The note should say so. The other option is that a paged list doesn't fetch the collection and only restricts the query to the instances.
2. JoinType.RIGHT in the fetch argument of list is applied as JoinType.INNER: 5 teams. At #17079, Team.list(fetch: [club: JoinType.RIGHT]) returns the 5 teams and a null for the club that no team refers to, and a where query with the same join type returns the null here as well. The note says that Hibernate 5 doesn't support right joins in these queries. After the merge-up, the two modules return different lists, which the note should name. Otherwise list could reject JoinType.RIGHT instead of returning other rows than requested.
3. "Results that change" should name point 1, and that a sort by the fetched association now keeps the instances without it, also with the setting off: Team.list(sort: 'club.name', fetch: [club: 'join']) returned 5 teams, and returns 7.
4. Add run ci, and resolve the conflicts with 7.0.x, as on the other parts. Locally, the tests of grails-data-hibernate5-core pass at this head (1385 tests, 54 skipped). The stack top returns what this head returns for all of these queries.
Notes
-
Player.list(fetch: ['team.players': 'join'], max: 2)works here. On 7.0.x it fails withUnable to locate Attribute with the the given name [team.players]. With Hibernate 7, on 8.0.x and at #17079, it fails withQuery specified join fetching, but the owner of the fetched association was not present. I'll raise that on #17079. -
On James's comment,
Team.list(sort: 'club.name', fetch: [club: JoinType.LEFT])returns all 7 teams here, as at #17079. The criteria query of the comment keeps them since #17069. -
Team.list(sort: 'players.name')still returns the team with three players three times, as on 7.0.x. #17079 returns each team once. That's a sort by a collection, which isn't this part's. -
No new public API here.
-
As a fix that changes a result, this needs a second reviewer (#17061).
Description
Part 11 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 #17070. Until that merges, this pull request also shows the commits below it. The change to review is the last commit, 66a5e5b.
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.
Results that change
list,findWhere,findAllWhereandfind/findAllwith an example apply a join type in theirfetchargument.listwithfetch: [author: 'join']fetches the association with an outer join and returns every instance, as a where query and a dynamic finder do.JoinType.INNERin thefetchargument to leave out the instances without the association.listis the one API that leaves out rows for the same fetch, which the dev@ thread settled for Hibernate 7: the fetch mode join of list() keeps the instances whose association is null or empty #16898; this is the Hibernate 5 side.The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry.
Verification
The association sort and join specs of
grails-data-hibernate5-corepass on this branch, withgrails.gorm.leftJoinAssociationSortoff and on, andcodeStylepasses for the touched modules. The full build was not run locally.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