Skip to content

Hibernate 7: return subclass rows when querying an intermediate class - #16470

Merged
jdaugherty merged 6 commits into
8.0.xfrom
fix/16464-h7-intermediate-subclasses
Oct 2, 2026
Merged

jdaugherty merged 6 commits into
8.0.xfrom
fix/16464-h7-intermediate-subclasses

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #16464

Problem

In a Hibernate 7 inheritance tree with three or more levels (Vehicle → Car → SportsCar / Sedan), queries on the intermediate class ignore the rows of its subclasses. Car.count(), Car.list(), criteria, dynamic finders and HQL return only the Car rows.

RootBinder added every subclass in the tree to the root RootClass. Hibernate finds a class's subclasses through its direct superclass (PersistentClass.getSubclasses() recurses through each class's direct subclasses), so the intermediate class had no subclasses in the mapping model.

Fixes

  • Hibernate 7, nested subclasses (grails-data-hibernate7: a query on an intermediate class of a table-per-hierarchy tree does not return the rows of its subclasses #16464): each subclass is now added to its own superclass. The root still sees the whole tree through Hibernate's recursion, with no duplicates. Hibernate 5 already binds subclasses this way (parent.addSubclass(subClass) in GrailsDomainBinder).
  • Hibernate 7, join table collections of a subclass: a unidirectional hasMany of a table-per-hierarchy subclass failed with Column "C1_0.CLASS" not found. HibernateToManyEntityOrderByBinder put the discriminator condition on the join table, which has no discriminator column. The condition is now only bound to one-to-many collections, as in Hibernate 5. This also affected two-level hierarchies.
  • MongoDB, loading by id through a subclass: Car.get(id) of a document saved as a Vehicle returned an object built from that document instead of null, because the id lookup did not restrict on _class like queries do. Both the codec and the mapping engine now apply the same _class restriction to the id lookup (MongoQuery.createClassFieldQuery). This also affected two-level hierarchies (City.get(location.id)).

Tests

  • TCK InheritanceSpec has a three-level hierarchy (FleetVehicle → FleetCar → FleetSportsCar / FleetSedan, plus a FleetGarage). It covers queries, loads and associations typed to the intermediate class, and loading a superclass instance through a subclass, on every GORM implementation.
  • IntermediateSubclassQuerySpec (Hibernate 7) covers all three inheritance strategies: queries and loads on the intermediate class, associations typed to it (lazy proxy, join fetch and collection), and root and leaf queries.
  • RootBinderSpec checks the direct subclasses of the root and of the intermediate class, and that the root sees each subclass once.
  • HibernateToManyEntityOrderByBinderSpec checks that the discriminator condition is bound to one-to-many collections and not to join table collections.
  • SubclassRetrieveByIdSpec (MongoDB) checks loading by id through each class of a hierarchy with both the codec and the mapping engine.

Each fix was mutation-checked: reverting it fails the new tests that cover it.

RootBinder added every subclass in an inheritance tree to the root class.
Hibernate resolves a class's subclasses through its direct superclass, so
an intermediate class had no subclasses in the mapping model: queries and
polymorphic loads on it ignored the rows of its subclasses.

Fixes #16464
@codecov

codecov Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.0342%. Comparing base (f0ddfef) to head (f604a6b).
⚠️ Report is 23 commits behind head on 8.0.x.

Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16470        +/-   ##
==================================================
+ Coverage     58.9446%   59.0342%   +0.0897%     
- Complexity      24451      24550        +99     
==================================================
  Files            2175       2175                
  Lines          107389     107668       +279     
  Branches        19562      19618        +56     
==================================================
+ Hits            63300      63561       +261     
- Misses          35223      35224         +1     
- Partials         8866       8883        +17     
Files with missing lines Coverage Δ
...ping/mongo/engine/MongoCodecEntityPersister.groovy 81.7391% <100.0000%> (+0.0797%) ⬆️
...ore/mapping/mongo/engine/MongoEntityPersister.java 43.3498% <100.0000%> (+3.0512%) ⬆️
...ails/datastore/mapping/mongo/query/MongoQuery.java 77.1354% <100.0000%> (-0.0300%) ⬇️
...ails/data/testing/tck/tests/InheritanceSpec.groovy 98.8372% <100.0000%> (+0.8780%) ⬆️

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

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

Review

Head: 69974f0c8a9cadadbe4c8de516574d154f7637b3 (fix/16464-h7-intermediate-subclasses)
Base: 8.0.x. The merge-base is the current base tip d13aa33282, so this is a clean single commit on top of it (3 files, +208/−3).

What I ran locally:

  • Full grails-data-hibernate7-core suite with --no-build-cache after cleanTest: 3344 tests, 0 failures, 0 errors, 30 skipped.
  • IntermediateSubclassQuerySpec and RootBinderSpec with only the RootBinder change reverted: 6 failures, as the description says. 5 are in IntermediateSubclassQuerySpec (the intermediate-class query feature for table-per-hierarchy and table-per-concrete-class, and the load-by-id feature for all three strategies). The 6th is the new RootBinderSpec feature. The joined query feature and the root/leaf features pass without the fix.
  • :grails-data-hibernate7-core:check -x test: Checkstyle and CodeNarc are clean.

Verdict: approve. The fix is correct and as small as it can be. The tests reproduce the issue for all three inheritance strategies. Everything below is optional.


Suggestions (non-blocking)

1. Cover an association typed to the intermediate class

The fix changes the mapping model that Hibernate uses for polymorphic associations, not only for queries. A test like Garage { Car car; static hasMany = [cars: Car] } would cover this. It would check that a SportsCar stored in car loads back as a SportsCar, proxied or not, and that cars holds both leaf types. That would lock in the path most likely to show up in a real application. It should fit into IntermediateSubclassQuerySpec with one extra domain class per strategy.

2. Consider a three-level hierarchy in the TCK

The TCK InheritanceSpec (grails-datamapping-tck/.../tests/InheritanceSpec.groovy) only has two-level trees (Location → City / Country). That is why this regression could exist in H7 while H5 was correct. If a Vehicle → Car → SportsCar / Sedan case went into the TCK, H5, H7 and MongoDB would all run it. This can be a follow-up; the H7-specific spec in this PR is fine on its own.

Nits

  • RootBinderSpec.groovy:30-31: the new org.hibernate.mapping.SingleTableSubclass and spock.lang.Issue imports sit before org.grails.datastore.mapping.core.connections.ConnectionSource. The file was already out of order, so maybe sort the block while touching it.

Verified as correct

  • Hibernate's subclass model: in Hibernate 7.4.10, PersistentClass.getSubclasses() and getSubclassSpan() recurse through each class's direct subclasses (subclasses.get(j).getSubclasses()). With the old code, the intermediate class had an empty list, so its persister saw no subclasses. Adding each subclass to subClass.getSuperclass() is the shape Hibernate expects.
  • No double registration: Subclass does not override addSubclass, so it does not also register the class on the root. The root therefore sees every subclass exactly once through the recursion. The new rootClass.subclasses.size() == 3 assertion covers this.
  • polymorphic flag: RootClass.addSubclass sets polymorphic = true. It is still called for every direct child of the root, so root polymorphism is unchanged.
  • Ordering: SubClassBinder.bindSubClass returns the subtree in pre-order, with each parent before its children. The Subclass constructor already has the correct superclass, so getSuperclass() is always set when addSubclass runs. With the fix, getSubclasses() also returns the order Hibernate documents, most derived subclasses first; before, the order was flat.
  • Consistency: this matches Hibernate's own EntityBinder (superEntity.addSubclass(subclass)) and H5 (GrailsDomainBinder.java:1582, parent.addSubclass(subClass)). Nothing else in grails-data-hibernate7 reads getSubclasses() / getDirectSubclasses() or calls addSubclass, so no other code depended on the flat registration.
  • Test isolation: the new spec follows the existing HibernateGormDatastoreSpec pattern. Each feature's data is rolled back by the TCK manager's cleanup(), and the root count of 4 in the third feature passes for every strategy.
  • Scope: grails-data-hibernate7 exists only on 8.0.x, so there is nothing to backport to 7.0.x. This is a bug fix with no user-facing API change, so no grails-doc update is needed.

…collections only

A collection of a table-per-hierarchy subclass is restricted by the
discriminator column. The condition applies to the collection table, so
a join table collection, such as a unidirectional hasMany, selected a
discriminator column the join table does not have. Hibernate 5 only adds
the condition to one-to-many collections, mapped by a foreign key in the
element's table.
Queries, loads and associations typed to an intermediate class now run
against every GORM implementation. MongoDB returns an instance of the
requested subclass when loading a superclass instance by id, so that
feature is pending there.
@testlens-app

This comment has been minimized.

Every class of an inheritance hierarchy shares its root's collection.
Queries restrict a subclass by _class, but loading by id did not, so
Car.get(id) of a document saved as a Vehicle returned an object built from
that document instead of null. Both the codec and the mapping engine now
apply the same _class restriction to the id lookup.
@jdaugherty
jdaugherty merged commit cc5bc9f into 8.0.x Oct 2, 2026
82 checks passed
@jdaugherty
jdaugherty deleted the fix/16464-h7-intermediate-subclasses branch October 2, 2026 13:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

grails-data-hibernate7: a query on an intermediate class of a table-per-hierarchy tree does not return the rows of its subclasses

2 participants