Skip to content

fix(hibernate): fetch join of to-one associations and criteria over basic-value collections - #16846

Open
borinquenkid wants to merge 11 commits into
8.0.xfrom
fix/fetch-join-and-element-collection-8.0.x
Open

borinquenkid wants to merge 11 commits into
8.0.xfrom
fix/fetch-join-and-element-collection-8.0.x

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Two query fixes for long-open issues, in both the Hibernate 5 and Hibernate 7 bindings. Each has unit specs in both core modules, a scenario in both example apps, and a docs note in createCriteria.

On Hibernate 7, an explicit select of the caller (fetchMode('destination', FetchMode.SELECT) of the criteria builder, or fetch: [destination: 'select'] of list) overrides the mapped join, and several restrictions in one block over basic values are tests of one element, compared by the column with its collation (ElementsInAll, an internal class of the module).

Branch policy: ElementsInAll is an internal class of the Hibernate 7 module, public only because the criteria builder and the predicate generator are in different packages, and the throw is the refusal of a property other than elements in a block over basic values, which this pull request adds with the block and which Hibernate 5 also refuses.

Fixes #14343
Fixes #14374

https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX

…st queries

findAll(), list() and the criteria builder ignored 'fetch: join' on a to-one
association, causing one extra select per row. H5 now adds a left fetch join
in the JPA list query; H7 does so in the HQL list builder and in the JPA
criteria creator. Associations without the mapping stay lazy.

Fixes #14343

Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
A criteria block named after a hasMany collection of enums or other basic
values threw MissingMethodException. The block now restricts the values
through the 'elements' property with eq and in, in both bindings.

Fixes #14374

Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
Copilot AI balanced review requested due to automatic review settings November 4, 2026 00:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@borinquenkid borinquenkid added this to the grails:8.0.1 milestone Nov 4, 2026
@borinquenkid
borinquenkid requested a review from matrei November 12, 2026 14:13

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not approving. Two restrictions in one collection block match different elements, and a paged count fails when a to-one is fetched.


public Object in(String property, Collection<?> values) {
requireElements(property);
return query.in(collection, new java.util.ArrayList<>(values));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kinds { eq('elements', Email); eq('elements', Phone) } matches a contact that has those kinds on different elements. Both tests must be of the same element.

if (property instanceof ToOne && !(property instanceof Embedded) && !explicitFetches.contains(property.getName()) &&
property.getMapping() != null && property.getMapping().getMappedForm() instanceof PropertyConfig &&
((PropertyConfig) property.getMapping().getMappedForm()).getFetchMode() == FetchMode.JOIN) {
queryRoot.fetch(property.getName(), JoinType.LEFT);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An entity with a join-mapped to-one, then list(max: 10).totalCount, throws. The count still fetches the association. Count without that fetch.

…e element, and the count of a paged list does not fetch

kinds { eq('elements', Email); eq('elements', Phone) } matched a contact that has those kinds on
different elements on Hibernate 7: each restriction was a test of its own. Every restriction of the
block is a test of the same element, as it is on Hibernate 5, so the restrictions now narrow one set
of values and are applied once, after the block: no element is both, and an in and an eq find the
element that satisfies both.

On Hibernate 5, list(max: n).totalCount threw for an entity with a to-one mapped fetch: 'join'
('query specified join fetching, but the owner of the fetched association was not present in the
select list'): the count reused the criteria of the list, with the fetch of the root in it. The count
is made without the fetches of the root.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Both cases reproduced, and are fixed in the new commit.

kinds { eq('elements', Email); eq('elements', Phone) } on Hibernate 7. Each restriction was a test of its own, so a contact with an Email element and a Phone element matched. I ran the case on Hibernate 5 first, as the reference: there the restrictions of the block test one element, so no element is both and the list is empty, and an in plus an eq find the element that satisfies both. The block now narrows one set of values with every eq, in and inList, and applies it once after the block; an empty set matches nothing. ElementCollectionCriteriaSpec has both shapes on both modules. The second row is built so that separate tests would pass it: a contact with [Email, None] has an element in [Email, Phone] and an element that is None, but no element that is both, so it must not be found.

list(max: 10).totalCount with a to-one mapped fetch: 'join' on Hibernate 5. It threw query specified join fetching, but the owner of the fetched association was not present in the select list. The count reused the criteria of the list, with the fetch of the root in it. It is made without the fetches of the root now. The criteria builder's list(max: n) already counted correctly, and so does Hibernate 7; the rows in FetchJoinToOneSpec are on both modules, for the static list and for the criteria builder.

The Hibernate 5 module (1,171 tests) and the Hibernate 7 module (4,302 tests) pass, and so does codeStyle.

Branch policy: the throw that is listed in CriteriaMethodInvoker, for a property other than elements on a collection of basic values, was already in this PR; this commit adds none. Where the PR belongs is still open; I have not moved it.

If you find another shape that does not reproduce first time, a failing spec on a throwaway branch, or the few lines you ran, would help me a lot.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. A block over basic values still drops a matching number when the two restrictions spell that number with different scales.

allowed = new java.util.LinkedHashSet<>(values);
}
else {
allowed.retainAll(values);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A collection holds 1.00. values { eq('elements', 1.0); eq('elements', 1.00) } should return that entity. It returns nothing, because 1.0 and 1.00 are not equal as Java values. Compare them as the stored number, not as Java objects.

@borinquenkid

Copy link
Copy Markdown
Member Author

The Hibernate 5 half is now #17055 against 7.0.x: neither fix changes a result that worked, so they go to the oldest branch with the bug (dev@ rule). This PR keeps the Hibernate 7 half; once the 7.0.x PR is merged and merged up, the Hibernate 5 files drop out of the diff.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@borinquenkid

borinquenkid commented Nov 21, 2026 •

Copy link
Copy Markdown
Member Author

@jdaugherty: fixes #14343 (open since 2023-08) and #14374 (open since 2022-02), in the Hibernate 5 and 7 bindings. Your read of the fetch-join and criteria handling would help.

@borinquenkid
borinquenkid marked this pull request as draft November 23, 2026 15:32
@borinquenkid

Copy link
Copy Markdown
Member Author

Back to draft: this PR changes CriteriaMethodInvoker, HqlListQueryBuilder and JpaCriteriaQueryCreator, which #17079 and #16863 change as well, so it waits for those two to merge and then rebases on them. I will mark it ready after the rebase and re-request review.

@borinquenkid
borinquenkid marked this pull request as ready for review November 23, 2026 16:51
@borinquenkid

Copy link
Copy Markdown
Member Author

Back to ready for review: this pull request was opened before #16863 and #17079, so it does not wait for them. If either of them merges first, I will merge the base into this branch and resolve the shared files.

… a number with different scales apply to the same stored number

values { eq('elements', 1.0); eq('elements', 1.00) } narrowed the allowed set with retainAll, which compares Java values, and
1.0 and 1.00 are not equal as BigDecimal, so a collection that holds 1.00 matched nothing. The values are compared as the
numbers they store.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Reproduced and fixed. The block narrowed its allowed values with retainAll, which compares Java values, and 1.0 and 1.00 are not equal as BigDecimal, so a collection that holds 1.00 matched nothing. The values are compared as the numbers they store (by compareTo, and for a value that has no decimal form such as NaN by equals). ElementCollectionCriteriaSpec has a BigDecimal collection with three cases: eq(1.0) and eq(1.00) find the entity, in([1.0, 2.0]) with eq(1.00) finds it, and eq(1.0) with eq(5.50) finds nothing; the first two fail without the change. The Hibernate 7 module (4350 tests) and codeStyle pass.

…lement-collection-8.0.x

# Conflicts:
#	grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/query/GrailsHibernateQueryUtils.java

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 6ff5cb0d1958675b18fc00ebf6b7075b6c99f6ea. The paged-count, same-element enum, and BigDecimal-scale fixes address the earlier reported cases. Two gaps remain.

1. Keep database equality for collection restrictions. CriteriaMethodInvoker.java:449-471 intersects nonnumeric values with Java equality before building SQL. For hasMany = [tags: String] under a case-insensitive collation, an element containing alpha satisfies both restrictions:

tags {
    eq('elements', 'alpha')
    eq('elements', 'ALPHA')
}

The Java intersection instead becomes empty, so the query rejects the matching entity. Please translate the conjunction against one database element and add a public criteria regression using a case-insensitive collation, retaining the tests that prevent different elements satisfying different restrictions.

2. Honor an explicit SELECT fetch mode. With destination fetch: 'join' in the mapping, Trip.createCriteria().list { fetchMode('destination', org.hibernate.FetchMode.SELECT) } still gets a fetch join. HibernateCriteriaBuilder.java:591-595 records SELECT in the detached fetch strategies, but JpaCriteriaQueryCreator.java:141-148 checks only eager fetch paths before applying the mapping. The caller cannot override the mapped join. Honor explicit fetch strategies and add a public criteria test verifying SELECT produces no fetch join while preserving the result rows.

Verification: an H2 predicate-only probe with SET COLLATION ENGLISH STRENGTH PRIMARY matched one stored row against both string predicates. Both GORM findings are source-traced; I have not executed these GORM reproducers.

Five files conflicted. The imports and the field of the spec keep both sides. The count of a paged list in Hibernate 5 takes
the version of 8.0.x, which handles a fetch of a collection and a sort through a fetched association. In Hibernate 7 the
mapped fetch join of a to-one association keeps its place next to the fetches that 8.0.x handles: the list applies it as a
left fetch join and the criteria apply it as a fetch with the join type the query requests, as a requested fetch is, and a
count has none because it has no entity to fetch into. The count of the HQL list is the one of 8.0.x.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

Merged 8.0.x to clear the conflicts; the merge changes nothing beyond resolving them.

  • HqlListQueryBuilder: this PR's mapped to-one fetch joins and the base's fetchesCollection() are both kept, and the mapped fetch joins are skipped for the count.
  • JpaCriteriaQueryCreator.applyRequestedJoins: a mapped to-one fetch uses the requested join type, or a left join, and is recorded as fetched.
  • H5 PagedResultList takes the base's count.

Both Hibernate modules compile and pass: Hibernate 5 core (3850 tests) and Hibernate 7 core (5422 tests), and codeStyle passes.

…sts of one element, compared by the column, and an explicit select overrides a mapped fetch join

- The restrictions of a block over a collection of basic values, tags { eq('elements', 'alpha'); eq('elements', 'ALPHA') }, were narrowed
  to the values they share as Java strings, so on a database whose collation takes the two for equal the entity that has the element
  was refused. A block of several restrictions is now a correlated subquery over the elements of the collection, whose element is one
  of the values of each restriction (ElementsInAll), so the database compares the column with the values: it applies the collation of
  the column and compares numbers as the numbers they store, and the Java narrowing of the values is gone. Restrictions that need
  different elements still do not satisfy each other.
- A to-one association that the mapping fetches with a join was fetch-joined also when the call names it with an explicit select, as
  fetchMode('destination', FetchMode.SELECT) does, so the caller could not override the mapping. An explicit select is honoured, with
  the rows unchanged.
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed the next commits, which answer the review of 12-03 at 6ff5cb0. Both gaps are in Hibernate 7 and both are fixed; I also merged 8.0.x first (no conflict).

1. Database equality for the restrictions of a block over basic values. You are right: tags { eq('elements', 'alpha'); eq('elements', 'ALPHA') } narrowed the two restrictions to the values they share as Java strings, so under a case-insensitive collation the entity that has the element was refused. A block of several restrictions is now one test of one element, written for the database: a correlated subquery over the elements of the collection, whose element is one of the values of each restriction (ElementsInAll, handled in PredicateGenerator). The database compares the column with the values, so it applies the collation of the column, as it does for a restriction of its own, and compares numbers as the numbers they store; the Java narrowing, with its decimal comparison, is gone. A block with one restriction is as it was, and restrictions that need different elements still do not satisfy each other. The first design I tried compared two literals with each other, which uses the collation of the database and not that of the column; an independent read of it found that, and the subquery replaced it.

ElementCollectionCollationSpec runs on an H2 database whose collation takes alpha and ALPHA for equal (COLLATION=ENGLISH STRENGTH PRIMARY in the URL, as in your probe). It has 17 rows: eleven combinations of restrictions (eq and eq with the same value in two cases, with different values, in and eq, in and in, three restrictions, an empty list, the same value twice), and the block directly, in an or, in an and, under a not, in an association block, and in an or in an association block. With the old code 12 of them fail. ElementCollectionCriteriaSpec, which keeps the rows that tell different elements from one element, and the number scales, passes as it was. H2 can set only the collation of the whole database, so I could not run a column whose collation differs from the default; the subquery compares the column, but that case is not tested.

2. An explicit SELECT fetch mode. Trip.createCriteria().list { fetchMode('destination', FetchMode.SELECT) } kept the fetch join of the mapping. JpaCriteriaQueryCreator.applyRequestedJoins now leaves the mapped join of a to-one association out when the query names it with a select (the fetch strategy is lazy), and the rows are the same. FetchJoinToOneSpec has a table of 23 rows: five query forms (the criteria builder, a detached criteria, the fetch argument of list, a where query, a dynamic finder), the association mapped with a join and one that is not, and none, select or join; each row checks the rows, the statements (a fetch join is one statement, a select of the association that is mapped eager is one for each location) and whether the association is loaded. Without the change the select row of the criteria builder fails.

Two things the table showed and I left alone: fetchMode(path, FetchMode.JOIN) of the criteria builder does not fetch a lazy association, and I measured the same on 8.0.x, so I excluded that row; and a select through a detached criteria, a where query or a finder returns the associated entities as a projection with Hibernate 7, which I have not measured on 8.0.x. Both are outside this pull request; I can open an issue for each.

grails-data-hibernate7-core passes (5524 tests) and codeStyle is clean.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

CriteriaBuilder doesn't work with ELEMENT_COLLECTION Domain class mapping with fetch: 'join' on OneToOne association results in n+1 queries

4 participants