Skip to content

fix(hibernate7): an association block that is a branch of or keeps the entities without the association - #16930

Open
borinquenkid wants to merge 14 commits into
8.0.xfrom
fix/h7-or-association-block-8.0.x
Open

borinquenkid wants to merge 14 commits into
8.0.xfrom
fix/h7-or-association-block-8.0.x

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

An association block inside or { } is one branch of the disjunction. The criteria guide documents it that way: "all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days". With Hibernate 7 the block is an inner join, so an account without transactions is dropped before the other branch can match it. A where query with || over an association does the same.

The setting

The fix changes the rows that common queries return, so it is behind grails.gorm.leftJoinAssociationInOr ("Fixes That Change a Result" in CONTRIBUTING.md), the same key as #16931:

default
8.0.x false
8.1.0 true (#17210)
9.0.0 removed (#17211)

An explicit false logs a startup warning naming Grails 9. With the setting unset or false, queries return what they return on 8.0.x.

With true:

  • A block in an or with more than one branch is a left join, so the other branches keep the instances without the association, also in count and totalCount.
  • The block still requires an associated entity that matches it. A block that names a left join, as in club(1) { isNull('name') }, does not require one, and a block that names an inner join keeps it.
  • A block outside an or, a block without criteria, the only branch of an or and a block in a not that is not inside an or require the association as before. That includes a not of more than one criterion: only an or keeps the instances without the association, as the upgrade note says.
  • A criterion on a dotted property, such as isNull('club.name'), requires the association as before, also beside a block on it in an or.

The join type of a block

Earlier commits applied the join type of a block through join() in AbstractDetachedCriteria. That reached every block of the same path, so club(1) { } inside an or also changed a club { } outside it, and it asked for the association to be fetched, with Hibernate 5 too. Now the join type is a property of the block, DetachedAssociationCriteria.requestedJoinType, which only Hibernate 7 reads, for a block in an or, with the setting.

Not changed

count and totalCount count a row for each matching element of a collection, as on 8.0.x.

A criterion on a dotted property inside a block in an or, as in mid { eq('leaf.name', 'x') }, requires the association of the block as well, as on 8.0.x. The upgrade note says so.

Order

#16931 adds the same setting on 7.2.x and goes first. The two add the same property to ConnectionSourceSettings; whichever meets the other in the merge up combines the two rows of the compatibility settings page and of the metadata.

Tests

CriteriaOrAssociationSettingHibernate7Spec runs a to-one association, a collection and a collection in a join table through a criteria query, a detached criteria, a where query, count and a paged list, with the setting unset, false and true, and the join types given to a block. Its unset and false rows, apart from those added later for the dotted property and the not, were also run against the 8.0.x sources and pass. CriteriaOrAssociationJoinTypeHibernate7Spec now runs with the setting, and HibernateDatastoreSpec pins the warning. grails-data-hibernate7-core (4,818 tests) and codeStyle pass on the head. grails-datamapping-core (1,831), grails-datamapping-core-test (692), grails-datastore-core (351), grails-data-hibernate5-core (1,899), grails-data-mongodb-core (1,034) and grails-core (1,170) passed two commits earlier; the later commits change only the Hibernate 7 module and documentation.

The shared specs, CriteriaOrAssociationSpec and CriteriaOrAssociationBlockSpec, and the in-memory store change are in #17188, stacked on this pull request. What an empty block means is #17174.

Fixes #16924
Evidence and the doc passage: #16924 (comment)

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

…e entities without the association

The criteria guide documents an association block inside or as one branch:
accounts that have either performed transactions OR were recently created.
The block was an inner join, so an account without transactions was dropped
before the other branch could match it. A block that restricts the
association, in an or with more than one branch, is now a left join. A block
outside an or, a block without criteria and the only branch of an or keep the
inner join.

Fixes #16924

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
Copilot AI balanced review requested due to automatic review settings November 11, 2026 15:15

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.

@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. An association block that accepts a null now matches an entity that has no association. The shared cases also fail on a datastore that still uses an inner join.

* performed transactions in the last 10 days OR have been recently created". An entity without the association is
* therefore found by the other branch. MongoDB has no association blocks.
*/
@IgnoreIf({ System.getProperty('mongodb.gorm.suite') == 'true' })

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.

The new shared cases run on a datastore that still uses an inner join for an association block. The to-one case returns only with, and the to-many case returns only Fred. Do not require that result from a datastore that has not changed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed. CriteriaOrAssociationBlockSpec is skipped on Neo4j now (and still on MongoDB), with the reason in its javadoc: Neo4j gets its fix in #16836, and that change removes the skip. Fixed in c7fc067.

…ociated entity

A null test in the block matched the entities without the association, because the
left join gives null for the missing one. The block now also requires the row of the
join on a left join. The shared block cases skip Neo4j until #16836 is merged.

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

@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.

A null test in an association block no longer matches an entity that has no association. Thread PRRT_kwDOAAfRJ862Qj3a resolved. Not approving. The same null test still matches when the association block is inside another block, and the shared cases still fail on a datastore that uses an inner join.

if (predicate == null) {
continue;
}
String path = branch instanceof DetachedAssociationCriteria<?> block && !block.getCriteria().isEmpty() ?

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.

or { and { child { isNull('name') } }; eq('name', 'nobody') }, where orphan has no child. The list returns orphan. The child block is not the direct branch, so the missing child is not rejected. Require the child there too.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@jamesfredley your findings from the 16:22 and 20:02 reviews:

The full Hibernate 7 suite passes.

… entity, and the shared cases skip Hibernate 5 until its fix is merged up

The row of the left join is required of any block with criteria inside an or with more than one branch, not only of a direct
branch, so or { and { child { isNull('name') } }; eq('name', 'nobody') } no longer returns an entity without a child.

@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.

A null test nested in an or no longer matches an entity that has no association. Not approving. An explicit left join no longer matches a missing association, and the shared case still fails on a datastore that has not changed.

}

then:
names(found) == ['orphan', 'with']

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.

or { eq('child', kid); eq('name', 'orphan') } returns only with on a datastore that still requires the association for the comparison. Do not require orphan from a datastore that has not changed.

…anner chose for an or, not to one the caller joined, and one shared case skips Hibernate 5

A caller that joins the association with a left join keeps the entities without it in the or; the TCK case that compares an
association to an instance in an or skips Hibernate 5 until its fix is merged up.

@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.

An explicit left join matches a missing association again. Thread PRRT_kwDOAAfRJ862b-EZ resolved. Not approving. A child with a composite id still matches when it is missing.

*/
private Predicate requireAssociated(JpaQueryContext context, String path, From<?, ?> joined, PersistentProperty<?> identity,
Predicate predicate) {
if (alternativesDepth > 0 && identity != null && context.isLeftForAlternatives(path) &&

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.

or { child { isNull('name') }; eq('name', 'nobody') }, where orphan has no child and the child's id is composite. The list returns orphan. The existence check is skipped because there is no single id. Require the child there too.

@borinquenkid
borinquenkid requested a review from matrei November 12, 2026 14:12
…and is no branch of an or

CriteriaOrAssociationBlockSpec expects an association block without criteria
to leave out the entities that have no associated entity, and to add no
branch to the or it stands in, as on the datastores that join. The in-memory
store matched nothing for the block and let the other branch of the or find
the orphan.

The block is now skipped as a branch and the whole result is restricted to
the entities that have an associated entity.

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

@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. An explicit inner join inside or becomes a left join, so an entity without the association is kept.

if (configured != null) {
return configured;
}
if (restricts && disjunctions > 0) {

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.

with has a child named kid. orphan has no child. or { child(0) { eq('name', 'kid') }; eq('name', 'orphan') } should return only with, because the caller asked for an inner join. It returns orphan and with. The numeric join argument is not recorded, so this treats the join as unconfigured and makes it a left join. Keep an explicit inner join.

…n entity with a composite id is required too

A block inside an or { } is built by the detached criteria, which read only a string alias from the
first argument, so child(0) { } lost its join type and the planner made it a left join: an entity
without the association matched. The block now joins the association with the type it names, as the
criteria builder does outside an or.

The existence check of a block that is a branch of an or took the identity property of the associated
entity, which an entity with a composite id does not have, so it was skipped. It uses the first id
property in that case.

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

Copy link
Copy Markdown
Member Author

@jamesfredley Both cases are fixed in the new commit, and my earlier answer on the join argument was wrong: it does reproduce.

or { child(0) { eq('name', 'kid') }; eq('name', 'orphan') }. The block of an or { } is built by the detached criteria, which read only a string alias from the first argument of a block, so the join type was dropped before the planner saw it and the planner made a left join. A block now joins its association with the type its first argument names (0 inner, 1 left, 2 right), the way the criteria builder does outside an or, so only with comes back. CriteriaOrAssociationJoinTypeHibernate7Spec runs the inner join through createCriteria() and through a detached criteria, and has child(1) { isNull('name') } finding orphan.

A child with a composite id. The existence check took the identity property of the associated entity, which an entity with a composite id does not have, so the check was skipped. It uses the first id property of the composite id now. The spec has an entity with a two-property id, where orphan no longer matches.

Four of the six rows in that spec fail without the change. The Hibernate 7 module (4631 tests), the Hibernate 5 module, the in-memory store, grails-datamapping-core and codeStyle pass. I also fixed an indentation codeStyle flagged in CriteriaOrAssociationBlockSpec.

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. An explicit inner join inside or is kept. A later left join on the same path still excludes a child that has no grandchild.

if (configured != null) {
return configured;
}
if (restricts && disjunctions > 0) {

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 earlier block marks grandchild as a left join that still requires the row. A later join('grandchild', LEFT) should keep the children that have no grandchild. It drops them, because the earlier mark is kept. Drop that mark when the caller names the join.

@borinquenkid

Copy link
Copy Markdown
Member Author

@jdaugherty: fixes #16924, a branch of an or with an association block that dropped the rows without the association, on Hibernate 7. You have committed most in this area, so your read of the or-branch handling would help.

…in the planner chose for an earlier block in an or

A block with criteria in an or is joined with a left join the planner chose, and the path was marked so the
entities without the association are still required by that block. A later block that names a join for the
same path kept the mark, so a left join the caller named still excluded the children without a grandchild.
Naming the join now drops the mark.

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

Copy link
Copy Markdown
Member Author

@jamesfredley Reproduced and fixed. A block in an or that has criteria is joined with a left join the planner chose, and the path was marked so that block still requires the associated entity. A later block that named a join for the same path kept that mark, so mid { join('leaf', LEFT) } still dropped the entities whose mid has no leaf. Naming the join for a path now drops the mark, in JoinPlan.configure.

CriteriaOrAssociationJoinTypeHibernate7Spec has the case (or { mid { leaf { isNull('name') } } ... } followed by mid { join('leaf', LEFT) }): it fails without the change and finds no-leaf with it. The Hibernate 7 module (4626 tests) and codeStyle pass.

@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. An empty or inside another or matches every owner that has the association.

}
}
}
if (resultList.results.isEmpty() && !criteriaList.isEmpty()) {

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.

or { or { child {} }; eq('name', 'wanted') } should match only an owner named wanted. It matches every owner that has a child, because the empty inner or is treated as true. An empty or matches nothing.

@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley I measured this on Hibernate 5, the reference, before changing anything, and the in-memory store matches it, so I am not changing this branch for it. or { or { child {} }; eq('name', 'wanted') } is a junction that holds only a block without criteria inside another junction. A block without criteria is a join and adds no condition, so the inner or is true and the entities without a child are left out of the whole result; an or that has no branches is true too. Hibernate 5 on 7.0.x returns, for owners with (has a child), wanted (has a child) and orphan (none):

  • or { or { child {} }; eq name wanted }, or { and { child {} }; eq name wanted } and or { or { or { child {} } }; eq name wanted }: wanted and with, every owner that has a child;
  • and { or { child {} }; eq name wanted }: wanted;
  • or { or {}; eq name wanted } and or { and {}; eq name wanted }: all three.

What does differ is Hibernate 7 on this branch, which returns only wanted for the first three, so its empty junction is not true there. That is the rule #17010, stacked on this pull request, fixes, and its table (CriteriaEmptyJunctionSpec, whose expected values are Hibernate 5's) now has the six nested shapes: or in or, and in or, or in or in or, or in and, each beside a name that matches and one that does not. The 58 rows pass on Hibernate 7 there. If you read Hibernate 5 differently for any of these shapes, tell me the owner and the criteria and I will measure that one.

@borinquenkid

Copy link
Copy Markdown
Member Author

The test behind those numbers, so that you can run it. Put it in grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/ on 7.0.x, with no change of mine on it, and run ./gradlew :grails-data-hibernate5-core:test --tests '*NestedOrEmptyBlockSpec':

package grails.gorm.tests

import org.apache.grails.data.hibernate5.core.GrailsDataHibernate5TckManager
import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec
import org.apache.grails.data.testing.tck.domains.ChildEntity
import org.apache.grails.data.testing.tck.domains.TestEntity

class NestedOrEmptyBlockSpec extends GrailsDataTckSpec<GrailsDataHibernate5TckManager> {

    def 'a junction that holds only an empty block is true on Hibernate 5'() {
        given: 'with and wanted have a child, orphan has none'
        new TestEntity(name: 'with', child: new ChildEntity(name: 'kid')).save(flush: true)
        new TestEntity(name: 'wanted', child: new ChildEntity(name: 'stranger')).save(flush: true)
        new TestEntity(name: 'orphan').save(flush: true)
        manager.session.clear()

        expect:
        TestEntity.withCriteria { or { or { child { } }; eq('name', 'wanted') } }*.name.sort() == ['wanted', 'with']
        TestEntity.withCriteria { or { and { child { } }; eq('name', 'wanted') } }*.name.sort() == ['wanted', 'with']
        TestEntity.withCriteria { and { or { child { } }; eq('name', 'wanted') } }*.name.sort() == ['wanted']
        TestEntity.withCriteria { or { or { }; eq('name', 'wanted') } }*.name.sort() == ['orphan', 'wanted', 'with']
    }
}

All four hold on Hibernate 5 as it is today. The same shapes, with the same expected values, are rows of the table in #17010 (CriteriaEmptyJunctionSpec), which Hibernate 7 passes there.

@borinquenkid

borinquenkid commented Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

This asks for an empty or inside another or to match nothing. Nothing documents what an empty or {}, and {} or association block means (the criteria guide only describes or { } with conditions in it, and #14635 asks for a query that is valid, not for a meaning), so what Hibernate 5 returns today is the behavior users have, and the other stores are being brought to it.

On Hibernate 5, or { or { child {} }; eq('name', 'wanted') } returns every owner that has a child as well as the one named wanted, because an empty junction is true wherever it stands: the row in CriteriaEmptyJunctionSpec is the value measured there, and #17010 makes Hibernate 7 the same. Making an empty or match nothing would change what Hibernate 5 returns for queries that run today, and is a change of its own: a separate issue, a setting, and an upgrade note, not a review point of this pull request. I'll open that issue if you want the meaning changed; until it is decided I would keep the table at the shipped values.

The test that shows it: CriteriaEmptyJunctionSpec in #17010, which stacks on this branch: line 124 or { or { child {} }; eq name=with } and line 127 or { or { child {} }; eq name=orphan }. Both expect ['other', 'with'], the owners that have a child, and pass on Hibernate 5 and on Hibernate 7 with #17010.

Sources:

The fix of this pull request is in Hibernate 7. The two shared specs that every
store runs, and the change of the in-memory store that lets them pass there,
move to their own pull request on top of this one, so that what a reviewer sees
here is what the title says.

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

Copy link
Copy Markdown
Member Author

This pull request is the Hibernate 7 fix only now. The two shared specs, CriteriaOrAssociationSpec and CriteriaOrAssociationBlockSpec, and the change of the in-memory store that passes them (SimpleMapQuery) are in #17188, stacked on this one. The finding of 11-24 about an empty or inside an or was on that in-memory change, and what an empty or means is #17174, a decision for every store, so it is not part of this pull request.

@matrei matrei 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.

First round, at d6fa6db. The branch merges cleanly with 8.0.x at a509055. CI hasn't run: the no ci label skipped all 46 checks.

I ran 46 queries with both modules of 8.0.x, at this head and at a509055. I also ran them with Hibernate 5 on 7.0.x (ffd848b) and at #16931 (ce1ec87). The fixture:

  • the teams Arsenal and Playerless play for the club Arsenal, Chelsea and Squad for Chelsea, and MU for Manchester United;
  • the teams Unattached and Empty have no club;
  • Squad has the players Squad A, Squad B and Squad C, Playerless and Empty have none, and the other teams have one each;
  • the club Teamless has no team, and the player Free Agent has no team.

I agree with the fix. The criteria guide describes the or as either branch, and the new rows below are what it describes. Hibernate 5 at #16931 returns the same rows as this head for each query in the first table.

The fix changes a result, so #17061 applies

8.0.x This head
Team.createCriteria().list { or { club { eq('name', 'Arsenal') }; eq('name', 'Unattached') } }, also as a detached criteria, with count(), and with max: 10 and its totalCount Arsenal, Playerless Arsenal, Playerless, Unattached
Team.where { club.name == 'Arsenal' || name == 'Unattached' }.list(), also with club { name == 'Arsenal' } Arsenal, Playerless Arsenal, Playerless, Unattached
or { isNull('club'); club { eq('name', 'Arsenal') } } Arsenal, Playerless also Unattached and Empty
not { or { club { eq('name', 'Arsenal') }; eq('name', 'MU') } } Chelsea, Squad also Unattached and Empty
or { players { eq('name', 'Squad A') }; eq('name', 'Empty') }, also as a where query Squad Squad, Empty
Player.createCriteria().list { or { team { eq('name', 'Squad') }; eq('name', 'Free Agent') } } the three players of Squad also Free Agent
Team.createCriteria().get { or { club { eq('name', 'Teamless') }; eq('name', 'Empty') } } null Empty

Hibernate 5 on 8.0.x gives the rows of the 8.0.x column, as it does on 7.0.x.

Under "Fixes That Change a Result" in CONTRIBUTING.md, this is a wrong result that many applications get:

  • an association block in an or, and a where query with || over an association, are common queries;
  • no other API returns the new rows yet: the where query, which asks for the same rows, returns the old ones too, with both modules.

So the fix needs a setting:

  • Default: off on 7.0.x, 7.1.x, 7.2.x and 8.0.x, on from 8.1.0, and removed in 9.0.0.
  • Key: the same as in #16931. That's the fix for the oldest branch with the bug, 7.0.x, so it goes first and is merged up. Merged alone, this branch makes Hibernate 7 return the new rows while Hibernate 5 on the same branch returns the old ones.
  • Warning: a warning at startup when an application sets the setting to keep the old rows.

The description should then say which results change, how an application gets the old ones, and why the fix needs a setting. The fix also needs:

  • a note in upgrading80x.adoc;
  • a row in compatibilitySettings.adoc;
  • the entry in the upgrade skill;
  • an issue for each of the two later steps.

This branch has only the sentence in the criteria guide. #16931 has a note and a skill entry for Hibernate 5. Both the note and the guide should name the where query, since the description speaks only of a block in or.

The change to AbstractDetachedCriteria reaches Hibernate 5

AbstractDetachedCriteria is in grails-datamapping-core, which every module uses. A block with a join type, such as players(1) { }, now calls join(name, type), and join also asks for the association to be fetched. For a detached criteria on 8.0.x, that's new:

Hibernate 5, 8.0.x Hibernate 5, this head Hibernate 7, 8.0.x Hibernate 7, this head
new DetachedCriteria(Team).build { players(1) { eq('name', 'Squad A') } }.list(), also with max: 1 Squad, its players not loaded Squad, holding only Squad A Squad, its players not loaded Squad, holding its three players
new DetachedCriteria(Team).build { or { players(1) { eq('name', 'Squad A') }; eq('name', 'Empty') } }.list() Squad Squad, holding only Squad A, and Empty Squad Squad, holding its three players, and Empty
new DetachedCriteria(Team).build { or { club(1) { eq('name', 'Arsenal') }; eq('name', 'Unattached') } }.list() Arsenal, Playerless also Unattached Arsenal, Playerless also Unattached
  • Hibernate 5: the description says this branch leaves it alone. But a detached criteria now returns other rows, and fills a fetched collection with only the elements that the block's criterion matches. The criteria builder of Hibernate 5 already does that for players(1) { eq('name', 'Squad A') }, on 7.0.x too, but its detached criteria didn't.
  • Hibernate 7: the rows are the ones the block asks for, but the collection is now fetched, also with players(0).

I didn't run MongoDB or Neo4j. I'd keep the change to Hibernate 7. Its or could read the join type of a block without asking for a fetch. If the shared change stays, it needs tests in grails-datamapping-core and with the other modules, and the note has to cover them.

A not with more than one criterion

With both modules, not { a; b } means not (a or b). Hibernate 7 builds it as criteriaBuilder.not(criteriaBuilder.or(...)) in PredicateGenerator.handleJunction. The planner counts only an or as alternatives, so two forms of the same query differ at this head:

8.0.x This head
not { or { club { eq('name', 'Arsenal') }; eq('name', 'MU') } } Chelsea, Squad Chelsea, Squad, Unattached, Empty
not { club { eq('name', 'Arsenal') }; eq('name', 'MU') } Chelsea, Squad the same as on 8.0.x

#16931 gives the same for Hibernate 5. I'd treat a not of more than one criterion as an or in both modules. If not, the note should say that only or keeps the entities without the association.

Tests

The fix's own rows are in #17188's shared specs, which are stacked on this branch. Here, only the changed row of SqlRestrictionHibernate7Spec has a block in or that finds an entity without the association. CriteriaOrAssociationJoinTypeHibernate7Spec covers the join types that a caller names and the existence check.

I'd add the to-one block, the to-many block and the where query of the first table to that spec, so that the fix is tested in the pull request that makes it. #17188 also waits for #16836.

What holds

  • The earlier reviews' points that I ran: or { club { isNull('name') }; eq('name', 'nobody') } returns nothing, and or { club(0) { eq('name', 'Arsenal') }; eq('name', 'Unattached') } keeps the inner join.
  • What still requires the association:
    • a block outside an or;
    • createAlias('club', 'c') before the or;
    • club { } before or after the or.
  • Other places the fix works:
    • a block nested in an and in the or;
    • a nested block, as in or { club { teams { eq('name', 'Squad') } }; eq('name', 'Empty') };
    • a sort by club.name;
    • a property projection.
  • Counts: for an association to a single instance, count() and totalCount count the rows that the list returns.

Smaller points

  • For #16931: with Hibernate 5, the left join of a to-many block in or fetches the collection, with the block's criterion. or { players { eq('name', 'Squad A') }; eq('name', 'Empty') } then returns Squad holding only Squad A, also as a where query. I'll raise that on #16931.
  • A to-many block in a criteria query (not new): Hibernate 7 lists each team once, but counts a row for each player. With or { players { eq('name', 'Squad A') }; eq('kind', 'team') }:
    • 8.0.x lists 5 teams and counts 7;
    • this head lists 7 and counts 9;
    • Hibernate 5 lists and counts 7 on 7.0.x, and 9 at #16931, with Squad three times.
  • James's review of 11-24 (an empty or inside an or): that's #17174, and #17010 covers Hibernate 7. I agree it's not for this pull request.

What I ran

As a fix that changes a result, this needs a second approval under #17061.

@sanjana2505006 sanjana2505006 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I ran this locally on Hibernate 7 and found one more case.

child(1) inside or { } now sets the join type of child for the whole query. So it also changes a child { } block outside the or:

OjParent.createCriteria().list {
    child { isNull('name') }
    or {
        child(1) { eq('name', 'kid') }
        eq('name', 'orphan')
    }
}

With with (child kid), other (child stranger) and orphan (no child), this returns orphan at this head, and nothing on 8.0.x (aa4de16). The outer block has no join type, so it should need a child, but it gets the left join from the or. If the two blocks are swapped, it returns nothing again, so the result depends on the order.

Maybe keep the join type on the block itself, instead of in the criteria's shared joinTypes?

I also see the same not and Hibernate 5 fetch results as matrei.

… of a block in or

The change returns more rows for common queries, so it is behind grails.gorm.leftJoinAssociationInOr, off by
default, and logs a warning when it is set to false. Without it, Hibernate 7 returns what 8.0.x returns.

A join type given to a block, as in club(1) { }, is now kept on the block instead of being applied through
join(), which reached every block of the path and asked for the association to be fetched. The Hibernate 7
planner applies it to a block in an or, with the setting.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…ation beside a block in an or

With grails.gorm.leftJoinAssociationInOr, the left join of a block in an or applied to every other use of the
same path, so isNull('club.name') outside the or matched the entities without a club. A dotted property of a
criterion now gives the path an inner join again. The upgrade note and the guide also say that a block in a not
that is inside an or is a branch of it.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… dotted property requires

The previous commit added the record to the join plan and did not call it, so its rows still failed.

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

Copy link
Copy Markdown
Member Author

@matrei Thanks. Done in 91a18da, with 8.0.x merged in:

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@borinquenkid

Copy link
Copy Markdown
Member Author

@sanjana2505006 Confirmed, and fixed in 91a18da. The join type of a block is now kept on the block instead of the shared join types, so child(1) inside or no longer changes a child { } outside it, in either order. The spec runs both orders through a criteria query and a detached criteria. The not and the fetch results that matrei listed are answered in the reply above.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@codecov

codecov Bot commented Nov 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.42857% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.9168%. Comparing base (42951ae) to head (91a18da).

Files with missing lines Patch % Lines
...orm/query/criteria/AbstractDetachedCriteria.groovy 71.4286% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16930        +/-   ##
==================================================
+ Coverage     62.9109%   62.9168%   +0.0059%     
- Complexity      27812      27822        +10     
==================================================
  Files            2252       2252                
  Lines          112157     112164         +7     
  Branches        20610      20613         +3     
==================================================
+ Hits            70559      70570        +11     
+ Misses          32185      32184         -1     
+ Partials         9413       9410         -3     
Files with missing lines Coverage Δ
.../query/criteria/DetachedAssociationCriteria.groovy 100.0000% <ø> (ø)
...g/core/connections/ConnectionSourceSettings.groovy 33.3333% <ø> (ø)
...orm/query/criteria/AbstractDetachedCriteria.groovy 79.5454% <71.4286%> (-0.1647%) ⬇️

... and 7 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@testlens-app

testlens-app Bot commented Nov 29, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 91a18da
▶️ Tests: 107336 executed
⚪️ Checks: 97/97 completed


Learn more about TestLens at testlens.app/docs.

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

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

An association block inside or { } drops the rows without the association on Hibernate 5 and 7

5 participants