Skip to content

fix(hibernate5): merge writes the changed fields of a detached instance, criterion in junction - #16845

Closed
borinquenkid wants to merge 13 commits into
8.0.xfrom
fix/h5-old-issues-batch-8.0.x
Closed

borinquenkid wants to merge 13 commits into
8.0.xfrom
fix/h5-old-issues-batch-8.0.x

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Two Hibernate 5 fixes for long-open issues. Neither changes a table, a column or a schema, so both fit a patch release. Each has a unit spec and a scenario in the grails-test-examples/hibernate5 app.

The joined-table inference for an abstract base class (#14423) and the schema and catalog of a joined subclass (#14427) change the tables of applications that work today, so they moved to a separate 8.1.x pull request.

Fixes #14354
Fixes #14370

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

Hibernate copies the state of a detached instance onto the managed one without GORM's
change tracking noticing, so the dirtiness strategy found nothing to flush and merge()
silently kept the old row. The properties the detached instance changed are now marked
on the merged one.

Fixes #14354

Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
…ed under an abstract base class

An abstract base class with the default strategy made a subclass that sets
tablePerHierarchy false a single-table subclass, while that subclass's own children
were joined, so loading them asked for a discriminator column the joined table does
not have. The abstract base class now follows the subclass and the hierarchy is joined.

Fixes #14423

Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
…og it declares

The table of a joined subclass always took the default schema, so a subclass that
declares its own schema was created, and queried, in the wrong one. It now uses the
schema and catalog from its table mapping, as the root class and the table-per-concrete
class subclass already do.

Fixes #14427

Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
…on joins that junction

add Restrictions.eq(...) inside or, and or not went to the root criteria, so it was
combined with AND whatever junction was open and the query returned the wrong rows.
It is now added to the open junction like any other restriction.

Fixes #14370

Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
Copilot AI balanced review requested due to automatic review settings November 3, 2026 23:33

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

if (criteria == null) createCriteriaInstance();

if ("add".equals(name) && args.length == 1 && args[0] instanceof Criterion) {

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.

Shouldn't this be a constant on HibernateQueryConstants ?

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.

Done in de4deaa: the name is now HibernateQueryConstants.METHOD_ADD.

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

Merging a detached instance keeps its dirty fields, and a criterion added inside a junction is stored on that junction. Not approving. An abstract root follows any child that sets tablePerHierarchy false, including a child mapped to another datasource, and the shared mapping then drops the discriminator for the other session factory. criteria.add(Restrictions.eq(...)).add(...) also throws, because add now returns the criterion.

… subclasses

add(Criterion) inside a criteria closure returns the builder again, so
add(a).add(b) chains. The abstract-root tablePerHierarchy scan ignores
subclasses mapped to other datasources. The method name is a constant on
HibernateQueryConstants.

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

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

Chained criteria.add returns the criteria. Thread PRRT_kwDOAAfRJ86z4Blz is resolved. A subclass on another datasource no longer changes this session factory's strategy. Thread PRRT_kwDOAAfRJ86z4Blt is resolved. Not approving. An abstract root with one joined child and an unconfigured child's subclass fails to start, and a strategy inferred for one datasource is written onto the mapped form the other datasource reuses.

bindClass(entity, root, mappings);

Mapping m = getMapping(entity);
if (m != null && entity.isAbstract() && m.getTablePerHierarchy() && hasTablePerSubclassChild(children)) {

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 abstract root, a child with tablePerHierarchy false, and an unconfigured child that has its own subclass fails while the session factory is built. The subclass stays single-table after the root discriminator is removed, and Hibernate throws MappingException: discriminator mapping required for single table polymorphic persistence. Apply the strategy through that child's subclass.

// an abstract base class that says nothing about its strategy follows a subclass that sets
// tablePerHierarchy false: the hierarchy is joined, as the subclass would be unable to be
// joined to a base class that keeps a discriminator column
m.setTablePerHierarchy(false);

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 root mapped to every datasource is set to tablePerHierarchy false while the default datasource is built, because one default-only child uses that strategy. The archive datasource then maps its own child as joined. Keep the inferred strategy on the datasource being built.

…s on the datasource being built

An abstract base class that says nothing about its strategy is joined when a subclass sets
tablePerHierarchy false. The binder wrote that into the mapping of the base class, which every
datasource shares, so a datasource built later saw a joined base class it never inferred, and the
unconfigured subclasses of an unconfigured child stayed single-table under a base class that had lost
its discriminator.

The inference now belongs to the binder, which builds one datasource, and every read of the strategy
goes through it: the whole hierarchy under an inferred base class is joined on that datasource only.

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

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed in d9cdbf8, on top of de4deaa. Both comments had one cause: the binder wrote the inferred strategy into the mapping of the base class, and that mapping is shared by every datasource.

  • Unconfigured child with its own subclass: its subclass read the child's mapping, which says nothing, and so stayed single-table under a base class with no discriminator. The strategy now applies to the whole hierarchy under an inferred base class, so the subclass is joined.
  • Base class mapped to every datasource: the default datasource no longer rewrites the shared mapping. The binder, which builds one datasource, records the base classes it inferred as joined, and every read of the strategy goes through that record. The archive datasource keeps its own child single-table.

InferredJoinedHierarchySpec covers the first (base class, joined child, unconfigured child, grandchild: the session factory builds, every level reads back, no discriminator column). InferredStrategyPerDataSourceSpec covers the second: the default datasource joins its child, and the archive datasource stores its child in the base table with a discriminator. Both fail on the previous head (the grandchild with No discriminator found, the archive child with a table of its own). The H5 core suite passes.

@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 unconfigured child now follows the strategy inferred for that datasource, and the inferred strategy is not written onto the shared mapped form. Not approving. An abstract root that declares its own strategy is still rewritten when a child declares a different one.

bindClass(entity, root, mappings);

Mapping m = getMapping(entity);
if (m != null && entity.isAbstract() && m.getTablePerHierarchy() && hasTablePerSubclassChild(children)) {

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.

Input: an abstract root that declares tablePerHierarchy true, and a child that declares tablePerHierarchy false. The root is still inferred as joined, so existing rows in the root table are no longer returned. Keep the explicit root strategy. Infer a strategy only when the root does not declare one.

…eps it

A base class that says tablePerHierarchy true, or tablePerSubclass false, was inferred as joined when a
subclass sets tablePerHierarchy false, and its own rows stopped being returned. Mapping now records
whether the strategy was declared, and only a base class that did not declare one follows its subclass.

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

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed in 7431c6c. Mapping now records whether the strategy was declared, so an abstract base class that declares tablePerHierarchy true or tablePerSubclass false keeps it, and only one that says nothing follows a subclass that sets tablePerHierarchy false. DeclaredRootStrategySpec covers both declarations and the silent base class; the two declared cases fail without the change. The full Hibernate 5 core suite passes.

@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 abstract root that declares its strategy through the mapping property keeps it. Not approving. The same declaration through the fluent mapping method is still not recorded, and add() no longer returns the criterion, so list() on that result throws.

*/
boolean tablePerHierarchyDeclared = false

void setTablePerHierarchy(boolean tablePerHierarchy) {

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.

Input: an abstract root configured with the fluent tablePerHierarchy(true), and a child that declares tablePerHierarchy false. The generated method assigns the field and skips this setter, so the declaration is not recorded and the root is still rewritten. Record the declaration on that path too.

// a Hibernate criterion belongs to the junction that is open, not to the root criteria;
// the call returns the builder so that add(a).add(b) chains as it did on the Criteria
addToCriteria((Criterion) args[0]);
return this;

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.

Input: createCriteria().add(a restriction).list(). add() now returns the builder, and list() throws because the criteria already exist. Return the criterion at the top level. Keep the builder only when the add is inside a junction.

… fluent tablePerHierarchy records the declaration (#16845)

add() on the criteria builder returned the builder everywhere, so createCriteria().add(a).list() threw because the criteria already existed. It now returns the Criteria at the top level, as it did before, and the builder only inside a junction.

Mapping's generated fluent tablePerHierarchy(boolean) assigned the field and skipped the setter, so a base class declared that way was still rewritten as joined. Mapping now has its own fluent method that goes through the setter.

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

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed in 3e2c168. add() returns the Criteria at the top level again, so createCriteria().add(a).list() works, and the builder only inside a junction. Mapping has its own fluent tablePerHierarchy(boolean) that records the declaration, as the setter does. The H5 core suite passes.

jamesfredley
jamesfredley previously approved these changes Nov 8, 2026

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

The fluent mapping method now records an explicit strategy, and add() returns the criterion at the top level, so list() on that result runs.

@borinquenkid borinquenkid removed the no ci label Nov 9, 2026
@borinquenkid
borinquenkid marked this pull request as draft November 9, 2026 03:37
@borinquenkid
borinquenkid marked this pull request as ready for review November 9, 2026 03:37
@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.3418%. Comparing base (4c1868d) to head (f7f1fc8).
⚠️ Report is 128 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
.../hibernate/AbstractHibernateGormInstanceApi.groovy 33.3333% 0 Missing and 4 partials ⚠️
...ernate/query/AbstractHibernateCriteriaBuilder.java 75.0000% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@               Coverage Diff                @@
##             8.0.x     #16845         +/-   ##
================================================
+ Coverage         0   62.3418%   +62.3418%     
- Complexity       0      27296      +27296     
================================================
  Files            0       2248       +2248     
  Lines            0     111479     +111479     
  Branches         0      20428      +20428     
================================================
+ Hits             0      69498      +69498     
- Misses           0      32641      +32641     
- Partials         0       9340       +9340     
Files with missing lines Coverage Δ
...ernate/query/AbstractHibernateCriteriaBuilder.java 39.3103% <75.0000%> (ø)
.../hibernate/AbstractHibernateGormInstanceApi.groovy 72.2449% <33.3333%> (ø)

... and 2246 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.

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

Ran this at 3e2c168 against 8.0.x. merge() of a detached instance with tracked changes is written, add inside a junction goes to that junction, and the datasource scoping and the declared-root handling hold up.

Three things need a change before this merges:

  • The schema must not change in 8.0.1. 8.0.0 is released, and the binder changes for #14423 and #14427 change the tables of applications that work today, so they belong on 8.1.x. The mappings affected are in the comments on lines 1533 and 1772 of GrailsDomainBinder.
  • A plain class must not be treated as a GORM entity. An abstract root that extends one is not recognised as inferred, so #14423 is not fixed for it. See the comment on rootClassOf.
  • merge() still drops changes when GORM has no list of changed names. See the comment on performMerge.

Upgrade notes. grails-doc is not part of this PR. Each behaviour change needs a note in the upgrade guide of the branch it lands on (upgrading81x.adoc for the binder changes), even where the old behaviour was a bug: what happened before, what happens now, and how to keep the old result.

  • merge() of a detached instance now writes its changed properties.
  • add(...) inside or, and or not now joins that junction instead of being ANDed at the root, so an or can return more rows. Moving the add out of the junction keeps the old result.
  • An abstract root that declares no strategy is joined when a direct child sets tablePerHierarchy false. Declaring tablePerHierarchy true on the root keeps one table.
  • A joined subclass is created in the schema and catalog its mapping has, including those inherited from its parent's mapping.

Hibernate 7. RootBinder has no equivalent of the inference, so the same mapping gives different tables on Hibernate 5 and Hibernate 7. Please say so in the upgrade note as well.

The other comments are smaller: branches the new specs do not reach, two fully qualified names, and the visibility of the new flag.

* mapping says nothing. It belongs to the binder, which builds one datasource: the mapping of a class is shared by
* every datasource, so the strategy a datasource infers is never written to it.
*/
private final java.util.Set<Class<?>> inferredJoinedRoots = new java.util.HashSet<>();

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.

Set and HashSet are already imported here, so neither needs the full name.

bindClass(entity, root, mappings);

Mapping m = getMapping(entity);
if (m != null && entity.isAbstract() && m.getTablePerHierarchy() && !m.isTablePerHierarchyDeclared() &&

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.

This changes the tables of applications that work today, so it should not ship in 8.0.1. Please move it to 8.1.x.

Mapping 8.0.x here
Abstract root, and a child with tablePerHierarchy false and no subclass below it one table, holding the child's columns and class a new table for the child, no class column
Abstract root that declares only discriminator column: 'kind', and the same child one table with kind a new table for the child, no kind column

Neither is the failure in #14423, which needs a subclass below the joined child. An application with a managed schema would have to add the table and move its rows to take a patch release.

return mapping.getTablePerHierarchy() && !inferredJoinedRoots.contains(rootClassOf(entityClass));
}

private static Class<?> rootClassOf(Class<?> entityClass) {

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 plain class must not be treated as a GORM entity, and this walk does that: it stops at the class just below Object, whether or not that class is an entity. inferredJoinedRoots holds the entity root, so for an abstract root that extends a plain class, the lookup in isTablePerHierarchy uses the plain class and never matches.

abstract class Plain { }                         // not a domain class

abstract class Root extends Plain { Long id }    // domain class

class Person extends Root {                      // domain class
    Long weight
    static mapping = { tablePerHierarchy false }
}

class Man extends Person { String firstName }    // domain class

The inference has no effect on this hierarchy. The tables are the same as on 8.0.x, with class and weight on the root table and Man joined to it, and saving a Man fails with NULL not allowed for column "VERSION".

Please resolve the root from the mapping model with PersistentEntity.getRootEntity() instead of walking the Java classes. getRootMapping has the same walk and returns no mapping for this hierarchy, so the collection check on line 443 needs it too. In a throwaway spec, an isAssignableFrom check over inferredJoinedRoots plus getRootEntity() in getRootMapping gave each class its own table, a Man saved and loaded through a collection, and the binder specs in this PR still passed.

Please add a spec for this hierarchy.

String schemaName = getSchemaName(mappings);
String catalogName = getCatalogName(mappings);
// the table the subclass declares itself wins over the default, as it does for its root class
Mapping subMapping = getMapping(sub);

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.

Mapping closures are inherited, so this also picks up a table schema: declared only on the parent. With a root that has table schema: 'x' and tablePerHierarchy false, and a child with no table of its own, the child table is in the default schema on 8.0.x and in x here. That is a schema change too, so this should move to 8.1.x with the inference.

JoinedSubclassSchemaSpec declares the schema on both classes. Please add the case where only the parent declares it, and one for the catalog branch below, which the new specs do not reach.

// Hibernate copies the state of a detached instance onto the managed one without GORM's change tracking
// seeing it, so the properties the detached instance changed are marked on the managed one; otherwise
// the dirtiness strategy finds nothing to flush.
List<String> changed = target instanceof DirtyCheckable ? ((DirtyCheckable) target).listDirtyPropertyNames() : []

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.

listDirtyPropertyNames() is empty when GORM has no list of changed names, although hasChanged() is true. Nothing is then marked on the merged instance and the row keeps its old values:

Instance passed to merge() 8.0.x here
Detached, with tracked changes not written written
new Foo(...) with the id of an existing row not written not written
Serialized and restored not written not written
markDirty() on the whole instance not written not written

The scenario in #14354 keeps the instance in the HTTP session, and $changedProperties is transient, so a session store that serializes takes the third row.

Please call markDirty() on the merged instance when hasChanged() is true and no names are listed, and add a spec for those three rows. In a throwaway spec that change writes all three, and MergeDetachedDirtyFieldsSpec still passes.

Changes to a child cascaded from the merged parent, and to an embedded object changed in place, are not written either, on 8.0.x or here. Those need a different mechanism, so a follow-up issue is fine.

List<String> changed = target instanceof DirtyCheckable ? ((DirtyCheckable) target).listDirtyPropertyNames() : []
hibernateTemplate.execute { Session session ->
Object merged = session.merge(target)
if (merged instanceof DirtyCheckable && !merged.is(target)) {

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 specs only merge a detached instance. Please add one for an instance the session already manages, where merged is target.

* Whether the mapping states its strategy, as opposed to leaving the default: a base class that states one keeps
* it, and only one that does not follows a subclass that sets {@code tablePerHierarchy false}
*/
boolean tablePerHierarchyDeclared = false

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.

Only the binder needs this, but as a property it is public and settable on Mapping. A private field with an isTablePerHierarchyDeclared() getter keeps it out of the API.

…marks an instance that reports a change without names

The inference of a joined hierarchy under an abstract base class and the schema and catalog
of a joined subclass change the tables of applications that work today, so they leave this
patch release; they continue on 8.1.x. merge() marks every property of the merged instance
when the detached one reports a change without naming the properties, as one restored from a
serialized session does. Specs cover a hand-made instance with the id of a row, a serialized
copy, a whole-instance markDirty(), and an instance the session already manages.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid borinquenkid changed the title fix(hibernate5): merge dirty fields, abstract tablePerHierarchy, subclass schema, criterion in junction fix(hibernate5): merge writes the changed fields of a detached instance, criterion in junction Nov 9, 2026
@borinquenkid

Copy link
Copy Markdown
Member Author

@jdaugherty all six are handled, in f7f1fc8.

The H5 core suite passes on both branches.

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

The fluent mapping method records an explicit strategy, and add() returns the criterion. Not approving. merge() of a new instance issues an update after the insert.

Object merged = session.merge(target)
if (merged instanceof DirtyCheckable && !merged.is(target)) {
if (changedWithoutNames) {
((DirtyCheckable) merged).markDirty()

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.

new MergeDirtyData(name: 'new', number: 1).merge(flush: true) inserts the row and then updates it. The version goes from 0 to 1. A new instance has no named dirty properties, so this marks the merged copy dirty after the insert. Leave a new instance alone after the insert.

Only a detached instance that reports a change without naming properties has all of its properties marked after the merge; a new instance is inserted and left alone.
@jdaugherty

Copy link
Copy Markdown
Contributor

Why are all of these tests being deleted?

@borinquenkid

Copy link
Copy Markdown
Member Author

@jdaugherty none of them are deleted. They moved with the code, as you asked ("binder part to 8.1.x"), in 793a1ad.

The joined-table inference, the schema and catalog change, and the tablePerHierarchy declaration left this pull request for #16904 (against 8.1.x). The specs that test that code left with it, and each one is in #16904 now:

  • AbstractRootDataSourceHierarchySpec
  • DeclaredRootStrategySpec
  • InferredJoinedHierarchySpec
  • InferredStrategyPerDataSourceSpec
  • JoinedSubclassSchemaSpec (extended there; a catalog spec was added next to it)
  • TablePerHierarchyFalseUnderAbstractSpec
  • the ScenarioInheritance* example domains, whose scenario is now JoinedHierarchyHibernate5ScenarioSpec

This pull request has no deleted test now: against 8.0.x it only adds files, and MergeDetachedDirtyFieldsSpec gains the cases for merge(). Keeping those specs here would test code this branch no longer has, and they would fail.

If you meant one spec that is not in that list, tell me which and I will check it.

@borinquenkid
borinquenkid requested a review from matrei November 12, 2026 14:13
@jamesfredley
jamesfredley dismissed their stale review November 13, 2026 02:29

The approval no longer holds: merge of a new instance can still be followed by an update, and add inside a junction returns the builder instead of the criterion.

@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. merge of a new instance can still be followed by an update, and add inside a junction returns the builder instead of the criterion.

// junction there is no Criteria to return, so the builder takes the next add
boolean inJunction = !logicalExpressionStack.isEmpty();
addToCriteria((Criterion) args[0]);
return inJunction ? this : criteria;

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.

Restrictions.eq('authorName', 'author1') passed to add inside or { } should come back as that criterion. add returns the builder, so the assertion that it is the criterion fails. The criterion is added. Return the criterion.

List<String> changed = target instanceof DirtyCheckable ? ((DirtyCheckable) target).listDirtyPropertyNames() : []
// a detached instance that reports a change without naming the properties, such as one restored from a
// serialized session, has all of its properties marked; a new instance is inserted and left alone
boolean changedWithoutNames = changed.isEmpty() && target instanceof DirtyCheckable &&

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 new instance whose id is a primitive long is 0, so this treats it as detached. After the insert, the managed copy is marked dirty and the flush issues an update. A new instance that already tracks a named change takes the other branch and is marked dirty the same way. Leave a new instance alone after the insert.

…rt, and add returns the criterion inside a junction

merge() took an instance for detached when its id was not null, so a new instance with a primitive id
(0) or one that already tracked a named change was marked dirty after the insert and updated. Hibernate's
own transient test decides now. Inside or, and and not, add(criterion) returned the builder; it returns
the criterion it added, and the Criteria at the top level as before.

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

Copy link
Copy Markdown
Member Author

@jamesfredley Both findings are fixed in the new commit.

merge() of a new instance. performMerge took an instance for detached when its id was not null, and a primitive long id is 0, so a new instance counted as detached and the merged copy was marked dirty after the insert. It asks Hibernate's own test now (ForeignKeys.isTransient: the id and version unsaved values, and a look at the row when it cannot judge), so a new instance is left alone after the insert whatever its id type or tracked changes. MergePrimitiveIdData (an entity with long id) is merged with flush: true: the version goes from 0 to 1 before the change and stays 0 now. A second case merges a new instance whose property was set after construction; that one passed before the change as well, so it is a guard and not a reproduction of your named-change case. If you have the exact sequence that updates, I will turn it into a case.

add inside a junction. Inside or, and and not, add(criterion) returns the criterion it added; at the top level it still returns the Criteria, so add(a).add(b) and add(a).list() work there. The case in HibernateCriterionInJunctionSpec that chained two add calls inside or is replaced by one that asserts each call returns the criterion it added and that both are part of the disjunction (it fails before the change).

The H5 module (1174 tests) and codeStyle pass.

@testlens-app

testlens-app Bot commented Nov 16, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 1375c4c
▶️ Tests: 110299 executed
⚪️ Checks: 99/99 completed


Learn more about TestLens at testlens.app/docs.

@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 criterion added inside a junction is kept. Merging a proxy throws, and a new instance with an assigned identifier is inserted and then updated.

// Hibernate's own test for an instance that merge() inserts: the id and version unsaved values, and for
// an id it cannot judge a look at the row. A new instance is left alone after the insert, whatever id
// type it has and whatever changes it tracks.
boolean inserted = ForeignKeys.isTransient(target.getClass().name, target, null, (SessionImplementor) session)

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.

Book.merge(bookProxy) used to merge the proxy. It now throws, because the proxy class is not a mapped name. A new instance with an assigned identifier and a version is inserted and then updated. Unwrap a proxy before this check, and do not mark a row that was just inserted.

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

Reviewed at 1375c4c (base 8.0.x). The merge base is 4c1868d, 233 commits behind 8.0.x; GitHub reports no conflicts, and CI passes on this head.

What I ran locally:

  • On this head: MergeDetachedDirtyFieldsSpec and HibernateCriterionInJunctionSpec (14 features). All pass.
  • The same specs on the merge base: 7 of the 14 fail (the four merge features that write a change, and three of the junction features), so they guard both fixes.
  • The same specs on 7.0.x (171db20), adapted to GrailsDataTckSpec: the same 7 fail there, plus one that fails for a reason unrelated to the fix (item 1). With this PR's main-code changes applied on top (the only conflict is the import block of AbstractHibernateGormInstanceApi), the 7 pass and that one still fails.
  • MergeDetachedDirtyFieldsSpec against Hibernate 7 on 8.0.x: all 8 features pass, so Hibernate 7 does not have #14354. Hibernate 7 has no Restrictions for #14370.
  • A throwaway spec for James's two open points from 11-17, on this head, on 8.0.x and on 7.0.x (item 3).

Needs a fix

  1. Branch. Both bugs are in Hibernate 5 on 7.0.x, where Hibernate 5 is the default and where most of the applications that hit them are. The old results contradict what the call asks for: merge() of a changed instance writes nothing, and or { add(...) } ANDs the criterion at the root. That is the kind of fix that goes to the oldest branch that has the bug and merges up, as the rule in the dev@ thread "Fixes that change results on patch and minor branches" says for an old result that contradicts the call (jdaugherty agreed to it there on 11-18). Please retarget to 7.0.x. On 8.0.x, Hibernate 7 has neither bug, so nothing is lost there.

    By the same rule neither fix needs a setting that keeps the old result: other APIs already give the new one. save(flush: true) of the same changed detached instance writes its changes on 8.0.x, and inside or { } the builder's own eq already joins the disjunction; only a criterion passed to add did not.

    On 7.0.x one feature fails for a reason unrelated to the fix: "merge of a new instance that tracks a named change is not followed by an update" builds new MergeDirtyData() with only name set, and on 7.0.x merge() validates first and returns null for the instance without number. Setting data.number = 1 keeps the feature about what it tests.

  2. Upgrade notes. jdaugherty asked on 11-09 for a note for each change in the upgrade guide of the branch the fix lands on, and the PR still has no grails-doc change. On 7.0.x that is a note under the release that carries the fix, and, as jdaugherty proposed in the same dev@ thread, the same entry in the upgrade skill (grails-skills/upgrade/skills/grails-upgrade/SKILL.md since #17033). Both fixes change results, so by that rule the PR also needs a second reviewer:

    • merge() of a detached instance now writes its changed properties, including an instance built by hand with the id and version of a row, one restored from a serialized copy, and one marked dirty as a whole. An application that changes an instance it keeps in the HTTP session, for example for display, and calls merge() only to attach it again, now writes those changes; discard() the changes, or reload the instance, to keep the row as it is.
    • add(...) inside or, and or not now joins that junction, so an or can return more rows. Inside a junction, add now returns the criterion it added instead of the Criteria, so or { add(a).add(b) }, which used to put both at the root, now throws MissingMethodException; two add calls are the replacement. Moving the add out of the junction keeps the old result.

Note

  1. James's two points from 11-17 are not from this PR:

    • A new instance with an assigned id, merged with flush: true, is inserted and then updated (its version ends at 1). That happens on 8.0.x and on 7.0.x too, with the same steps, so it is a separate issue.
    • Merging a proxy: Foo.merge(Foo.load(id)) with the proxy still attached merges here, as it does on 8.0.x. A proxy that was never initialized and whose session is gone throws LazyInitializationException on 8.0.x and here alike.

    If James has a case that passes on 8.0.x and fails here, that one needs a look; the ones I could build do not.

Verified as correct

  • ForeignKeys.isTransient (AbstractHibernateGormInstanceApi.groovy:467) leaves a new instance alone after the insert: the primitive long id case and the tracked-change case both keep version 0.
  • An instance the session already manages is returned as is (merged.is(target)), so nothing is marked twice.
  • At the top level add still returns the Criteria (AbstractHibernateCriteriaBuilder.java:1804), so add(a).add(b) and add(a).list() work as on 8.0.x.
  • The example app scenario covers both fixes through a running application.

@borinquenkid

Copy link
Copy Markdown
Member Author

Retargeted as #17044 on 7.0.x, as you asked: both bugs are in Hibernate 5, and Hibernate 7 on 8.0.x has neither. A pull request cannot change its base to a branch whose history this one does not share without carrying the 233 commits in between, so it is a new pull request with the same two fixes as one commit. I will close this one when the new one is open, and the merge-up carries the fix to 8.0.x.

What changed from this head, for your points:

  1. Branch and results. On 7.0.x. No setting keeps the old result, as you wrote. The spec that failed on 7.0.x for an unrelated reason (merge of a new instance built without number) sets number. The specs extend GrailsDataTckSpec, as the other Hibernate 5 specs of 7.0.x do. The only conflict was the import block of AbstractHibernateGormInstanceApi; the imports that 7.0.x does not use are removed.
  2. Upgrade notes. One note for each fix under 7.0.18 in the upgrade skill, with what to search for: the merge() that attaches an instance changed for display, the add(...) that now joins its junction, and or { add(a).add(b) }, which now throws MissingMethodException. The guide of this repository has no per-release page for 7.x, so the skill is where they are.
  3. Notes on James's two points. Agreed that they are not from this change: a new instance with an assigned id that is merged with flush: true is inserted and then updated on 7.0.x and 8.0.x alike, and merging a proxy behaves as on 8.0.x. I will open the first as an issue.

Two reviewers are needed on 7.0.x for a change that alters results; the new pull request requests the usual five.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@borinquenkid

Copy link
Copy Markdown
Member Author

Superseded by #17044 (7.0.x).

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

Labels

None yet

Projects

Status: Done

5 participants