Repository navigation
Hibernate 7: return subclass rows when querying an intermediate class - #16470
Conversation
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 Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
matrei
left a comment
There was a problem hiding this comment.
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-coresuite with--no-build-cacheaftercleanTest: 3344 tests, 0 failures, 0 errors, 30 skipped. IntermediateSubclassQuerySpecandRootBinderSpecwith only theRootBinderchange reverted: 6 failures, as the description says. 5 are inIntermediateSubclassQuerySpec(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 newRootBinderSpecfeature. 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 neworg.hibernate.mapping.SingleTableSubclassandspock.lang.Issueimports sit beforeorg.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()andgetSubclassSpan()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 tosubClass.getSuperclass()is the shape Hibernate expects. - No double registration:
Subclassdoes not overrideaddSubclass, so it does not also register the class on the root. The root therefore sees every subclass exactly once through the recursion. The newrootClass.subclasses.size() == 3assertion covers this. polymorphicflag:RootClass.addSubclasssetspolymorphic = true. It is still called for every direct child of the root, so root polymorphism is unchanged.- Ordering:
SubClassBinder.bindSubClassreturns the subtree in pre-order, with each parent before its children. TheSubclassconstructor already has the correct superclass, sogetSuperclass()is always set whenaddSubclassruns. 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 ingrails-data-hibernate7readsgetSubclasses()/getDirectSubclasses()or callsaddSubclass, so no other code depended on the flat registration. - Test isolation: the new spec follows the existing
HibernateGormDatastoreSpecpattern. Each feature's data is rolled back by the TCK manager'scleanup(), and the root count of 4 in the third feature passes for every strategy. - Scope:
grails-data-hibernate7exists only on8.0.x, so there is nothing to backport to7.0.x. This is a bug fix with no user-facing API change, so nograils-docupdate is needed.
…mediate-subclasses
…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.
This comment has been minimized.
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.
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 theCarrows.RootBinderadded every subclass in the tree to the rootRootClass. 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
parent.addSubclass(subClass)inGrailsDomainBinder).hasManyof a table-per-hierarchy subclass failed withColumn "C1_0.CLASS" not found.HibernateToManyEntityOrderByBinderput 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.Car.get(id)of a document saved as aVehiclereturned an object built from that document instead ofnull, because the id lookup did not restrict on_classlike queries do. Both the codec and the mapping engine now apply the same_classrestriction to the id lookup (MongoQuery.createClassFieldQuery). This also affected two-level hierarchies (City.get(location.id)).Tests
InheritanceSpechas a three-level hierarchy (FleetVehicle→FleetCar→FleetSportsCar/FleetSedan, plus aFleetGarage). 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.RootBinderSpecchecks the direct subclasses of the root and of the intermediate class, and that the root sees each subclass once.HibernateToManyEntityOrderByBinderSpecchecks 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.