Repository navigation
fix(hibernate5): fail fast when a SCHEMA multi-tenant entity references an entity no tenant schema maps - #17276
borinquenkid wants to merge 10 commits into
Conversation
… no tenant schema maps With SCHEMA multi-tenancy only MultiTenant entities are mapped into each tenant schema's SessionFactory, so an association from a MultiTenant entity to another entity failed at startup with 'refers to an unmapped class'. HibernateDatastore now throws a ConfigurationException that names each Owner.property -> Target and says how to fix it. Fixes #14345 Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…HibernateDatastore The patch line adds no public methods: the finder that was a public static method of ConnectionSourcesSupport is now private code in HibernateDatastore. Its spec of the shared class goes with it; the Hibernate 5 specs cover the check through the datastore. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…excludes a tenant schema The startup check skipped every multi tenant target, so an owner mapped on a tenant schema that a multi tenant target excludes with @TenantDataSourceConfig was accepted, and the tenant session factory was built with an association to an entity it does not map. A multi tenant target is now asked whether it is mapped on every connection that maps the owner, as any other target is. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…s a tenant schema is refused whatever else its mapping says Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…t startup With SCHEMA multi-tenancy and an AllTenantsResolver that returns no tenant at startup, an association between multi tenant entities was refused, although a tenant added later maps both. A multi tenant target is accepted there. The message no longer says the target is not multi tenant, which is wrong when it is multi tenant and excludes a schema. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
There was a problem hiding this comment.
🟡 Changes recommended
The new association checks can incorrectly reject valid basic-value mappings, subclass tenant configurations, and JPA multi-tenant targets, preventing previously valid applications from starting.
3 open issues
What changed in this PR
Improves Hibernate 5 SCHEMA multi-tenancy startup diagnostics for unsupported associations, addressing part of #14345 without adding association support.
Changes:
- Adds private validation that identifies associations whose targets are missing from tenant mappings.
- Adds startup tests covering mapping layouts, exclusions, and tenants added later.
- Documents mapping requirements and the 7.0.18 startup behavior change.
| File | Description |
|---|---|
| grails-doc/src/en/guide/upgrading/upgrading60x.adoc | Adds the upgrade warning. |
| grails-data-hibernate5/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc | Explains association mapping requirements. |
| grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationSpec.groovy | Tests diagnostics and delayed tenant creation. |
| grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationLayoutSpec.groovy | Tests datasource layouts and exclusions. |
| grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java | Validates associations before creating tenant session factories. |
Review effort: Balanced
| if (!(property instanceof Association) || property instanceof Embedded || property instanceof EmbeddedCollection) { | ||
| continue; | ||
| } | ||
| PersistentEntity target = ((Association<?>) property).getAssociatedEntity(); | ||
| if (target != null && !isMappedWhereOwnerIs(entity, target, tenantSchemaNames)) { |
There was a problem hiding this comment.
All three findings reproduce, and fb6765d fixes them. Each layout is a row of SchemaTenantAssociationLayoutSpec; it fails at startup on the previous head with the new ConfigurationException and starts on 7.0.x:
- A property declared with a domain type but bound as a basic value (a custom
UserType, ortype: 'serializable'on ahasMany) is left out of the check, asGrailsDomainBinderbinds it as aSimpleValue. - A subclass of a root that excludes the schema is checked against the connection sources of every ancestor, since
TenantDataSourceConfigis not inherited and the binder maps a subclass only through its root. - A JPA-annotated target is mapped on every schema whether or not it is multi tenant, as
buildSessionFactory()adds it to every session factory.
The Hibernate 5 module runs 1401 tests with 0 failures, and codeStyle is clean. Not covered: a JPA-annotated subclass inside a hierarchy is not handled specially, and the serializable type on a ToMany is read from the property's own type only.
| Set<String> names = new LinkedHashSet<>(tenantSchemaNames); | ||
| names.add(ConnectionSource.DEFAULT); | ||
| for (String name : names) { | ||
| if (ConnectionSourcesSupport.usesConnectionSource(owner, name) && !isMappedOn(target, name)) { |
There was a problem hiding this comment.
All three findings reproduce, and fb6765d fixes them. Each layout is a row of SchemaTenantAssociationLayoutSpec; it fails at startup on the previous head with the new ConfigurationException and starts on 7.0.x:
- A property declared with a domain type but bound as a basic value (a custom
UserType, ortype: 'serializable'on ahasMany) is left out of the check, asGrailsDomainBinderbinds it as aSimpleValue. - A subclass of a root that excludes the schema is checked against the connection sources of every ancestor, since
TenantDataSourceConfigis not inherited and the binder maps a subclass only through its root. - A JPA-annotated target is mapped on every schema whether or not it is multi tenant, as
buildSessionFactory()adds it to every session factory.
The Hibernate 5 module runs 1401 tests with 0 failures, and codeStyle is clean. Not covered: a JPA-annotated subclass inside a hierarchy is not handled specially, and the serializable type on a ToMany is read from the property's own type only.
|
|
||
| private static boolean isMappedOn(PersistentEntity target, String connectionSourceName) { | ||
| return ConnectionSourcesSupport.usesConnectionSource(target, connectionSourceName) || | ||
| (!target.isMultiTenant() && isMappedByJpaAnnotation(target)); |
There was a problem hiding this comment.
All three findings reproduce, and fb6765d fixes them. Each layout is a row of SchemaTenantAssociationLayoutSpec; it fails at startup on the previous head with the new ConfigurationException and starts on 7.0.x:
- A property declared with a domain type but bound as a basic value (a custom
UserType, ortype: 'serializable'on ahasMany) is left out of the check, asGrailsDomainBinderbinds it as aSimpleValue. - A subclass of a root that excludes the schema is checked against the connection sources of every ancestor, since
TenantDataSourceConfigis not inherited and the binder maps a subclass only through its root. - A JPA-annotated target is mapped on every schema whether or not it is multi tenant, as
buildSessionFactory()adds it to every session factory.
The Hibernate 5 module runs 1401 tests with 0 failures, and codeStyle is clean. Not covered: a JPA-annotated subclass inside a hierarchy is not handled specially, and the serializable type on a ToMany is read from the property's own type only.
…ciations out of the tenant schema check The check refused three layouts that start on 7.0.x: a property the binder maps as a basic value (custom type, serialized collection), an owner whose root excludes a tenant schema while it does not repeat the exclusion, and a JPA annotated target that is also MultiTenant and excludes a schema. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A valid association is still rejected when no tenant exists at startup.
| */ | ||
| private static boolean isMappedWhereOwnerIs(PersistentEntity owner, PersistentEntity target, Collection<String> tenantSchemaNames) { | ||
| if (tenantSchemaNames == null || tenantSchemaNames.isEmpty()) { | ||
| return target.isMultiTenant() || ConnectionSourcesSupport.getConnectionSourceNames(target).contains(ConnectionSource.ALL) || isMappedByJpaAnnotation(target); |
There was a problem hiding this comment.
No tenant exists at startup, and the owner excludes the tenant that is added later. The target is mapped on every connection that maps the owner. Startup should continue. It fails, because this ignores that exclusion. Keep the association.
There was a problem hiding this comment.
This is kept on purpose; no change pushed.
With no tenant at startup, a target that is not multi tenant, and that neither uses every connection (ALL) nor is a JPA entity, is not mapped in any schema added later. The owner is mapped in every tenant schema it does not exclude, so an owner that excludes one named tenant is still mapped in all the others.
Adding a schema while the application runs is documented: schemaPerTenant.adoc says "If you wish to add a schema whilst the application is running then you can use the addTenantForSchema of the HibernateDatastore class." So no tenant at startup does not mean no tenant ever, and the later schemas are the ones the association needs the target in.
The case in the review would be accepted only if every later tenant were one the owner excludes. Nothing in the mapping says that, so the check cannot know it. The spec "an association to an entity that is not multi tenant is refused when there is no tenant at startup" holds this behavior, and the message names the association and the ways out (a multi tenant target, datasource 'ALL', naming each schema, or the DISCRIMINATOR mode).
If you have a layout where the later tenants are bounded, tell me which and I will add a row for it.
jdaugherty
left a comment
There was a problem hiding this comment.
Reviewed the diagnostic-only scope of #14345 at fb6765d. All 28 cases in SchemaTenantAssociationSpec and SchemaTenantAssociationLayoutSpec passed on JDK 17 with H2. The new check nevertheless rejects three previously valid mapping layouts: class/default serialized-collection registrations, XML-mapped targets, and a default-only ancestor association when no tenants are initially present. These are compatibility regressions in the check, reproduced against the merge base; details are inline. The named-datasource remedy also needs the case-sensitive name DEFAULT.
The same eight public-API startup probes ran on merge base 0cea54a and on this head. The base passed seven; the lowercase-default control failed on both revisions. The head had five additional failing cases covering the three regressions. The uppercase DEFAULT control passed on both. Where applicable, the base also successfully added tenant1 and tenant2 after startup. Full module suites were not run.
| Object type = mappedForm instanceof PropertyConfig ? ((PropertyConfig) mappedForm).getType() : null; | ||
| if (type == null) { | ||
| return false; |
There was a problem hiding this comment.
[P2] Resolve class-level collection types before rejecting the association
A MultiTenant owner with Set<Target> targets, hasMany = [targets: Target], and mapping { 'user-type'(class: Set, type: 'serializable') } has no property-specific type here. The existing binder resolves the class registration through getTypeName() and binds the collection as a basic value, so a serializable, default-only Target does not need a tenant mapping. With tenant1 known, this layout starts at the merge base but now throws ConfigurationException for Owner.targets -> Target. I reproduced the same regression with the registration supplied through grails.gorm.default.mapping. Honor the binder's effective collection type rather than returning false solely because PropertyConfig.type is absent.
There was a problem hiding this comment.
Fixed in 4b76caa. The check now reads the type of a property the way the binder does: the type of its own mapping, or else the one that the mapping of its class registers for the class of the property, also when it comes from grails.gorm.default.mapping. A Set with 'user-type'(class: Set, type: 'serializable') is bound as a basic value, so its target need not be mapped.
SchemaTenantAssociationCompatSpec has the rows: the class-level registration with the tenant schemas known and with none, and the one from the default mapping. All three fail at fb6765d with the ConfigurationException and pass here.
| } | ||
|
|
||
| private static boolean isMappedOn(PersistentEntity target, String connectionSourceName) { | ||
| return isMappedByMappingOn(target, connectionSourceName) || isMappedByJpaAnnotation(target); |
There was a problem hiding this comment.
[P2] Recognize targets already mapped by configured Hibernate XML
A plain GORM Target can be mapped in every tenant SessionFactory by an explicit Target.hbm.xml supplied through hibernate.mappingLocations, even without a datasource declaration or JPA annotation. The connection factory retains and loads those resources for tenant factories, but this predicate reports the target as absent. I reproduced a MultiTenant Owner -> Target association that starts with tenant1 on the merge base and now fails with the new ConfigurationException. With an initially empty resolver, the base also starts and successfully adds both tenant1 and tenant2; this head rejects it at startup. Account for existing XML mappings before declaring the target unmapped.
There was a problem hiding this comment.
Fixed in 4b76caa. The check reads the names of the classes that the resources of hibernate.mappingLocations and hibernate.cacheableMappingLocations map (class, subclass, joined-subclass and union-subclass, with the package of the mapping), and takes such a target as mapped on every connection. When a configuration file, a jar or a directory of mappings is configured, which it does not read, it takes every target as mapped, so it never refuses what it cannot see.
SchemaTenantAssociationCompatSpec has the rows with an hbm.xml for the target, with the tenant schemas known and with none, and the control without the resource, which is still refused. The two rows with the resource fail at fb6765d.
| */ | ||
| private static boolean isMappedWhereOwnerIs(PersistentEntity owner, PersistentEntity target, Collection<String> tenantSchemaNames) { | ||
| if (tenantSchemaNames == null || tenantSchemaNames.isEmpty()) { | ||
| return target.isMultiTenant() || ConnectionSourcesSupport.getConnectionSourceNames(target).contains(ConnectionSource.ALL) || isMappedByJpaAnnotation(target); |
There was a problem hiding this comment.
[P2] Preserve guaranteed ancestor mappings with an empty tenant list
Consider a plain default-only SharedRoot and TenantChild extends SharedRoot implements MultiTenant<TenantChild> with a SharedRoot linkedRoot property. With an empty AllTenantsResolver, the merge base starts and successfully adds tenant1 and tenant2, but this branch throws for TenantChild.linkedRoot -> SharedRoot. The same hierarchy passes this head's check when tenant1 is already known. The binder can map the child only through its root, so every factory that maps the owner necessarily maps this target; this is not a prediction about future tenant names or a finite list of exclusions. Preserve that co-mapping guarantee in the empty-list branch instead of checking only the target's standalone flags.
There was a problem hiding this comment.
Fixed in 4b76caa. With no tenant at startup, a target in the hierarchy of the owner (the same root) is accepted: the binder maps a subclass only through its root, so every connection that maps the owner maps the root and the rest of the hierarchy. This is the guarantee you describe and not a guess about later tenant names.
The row in SchemaTenantAssociationCompatSpec starts SharedRoot and TenantChild extends SharedRoot with an empty resolver, then adds tenant1 and tenant2; it fails at fb6765d. A default-only entity outside the hierarchy is still refused with no tenant, and has a row.
|
|
||
| ==== Associations to Entities That Are Not Multi-Tenant | ||
|
|
||
| Each tenant schema gets its own `SessionFactory`, which maps the entities that implement `MultiTenant` and every other entity whose mapping uses that schema's connection: one that declares `datasource 'ALL'`, or one that lists the schema by name. The default connection maps the `MultiTenant` entities too, so a target that is not `MultiTenant` has to be mapped there as well: list `default` together with the tenant schemas, or use `ALL`. An entity that implements `MultiTenant` can have a `hasMany` or a to-one association to such an entity only when every connection that maps the owner maps the target. When one does not, the association has nothing to refer to: GORM refuses to start and names the associations, for example `Vehicle` in `TenantUser.vehicles -> Vehicle`. Make the target entity implement `MultiTenant` as well, map it on every tenant schema, or use the `DISCRIMINATOR` mode, which keeps every entity in the same tables. The check runs against the tenant schemas known at startup, so a schema added later has to map the target too: use `datasource 'ALL'` when tenants can be added at runtime. An entity that implements `MultiTenant` is not mapped on a tenant schema that its `@TenantDataSourceConfig(dataSourcesToExclude = [...])` excludes, even when it also declares `datasource 'ALL'`, so an association to it from an owner that is mapped there is refused in the same way. Embedded associations are not affected. |
There was a problem hiding this comment.
[P3] Spell the default connection as DEFAULT in the remedy
The datasource names are case-sensitive here. Following this guidance with datasources(['default', 'tenant1']) leaves the target out of the default SessionFactory and fails with Hibernate's unmapped-class MappingException before this check runs. I tested datasources(['DEFAULT', 'tenant1']) with the same MultiTenant owner and plain target: it starts successfully on both the merge base and this head. Use DEFAULT in the instructions and exercise the uppercase named-list layout; the lowercase spelling in the currently unused fixture explains that failure rather than a lack of Hibernate 5 support.
There was a problem hiding this comment.
Fixed in 4b76caa. The guide and the message now say DEFAULT, and that the names are case-sensitive. The fixtures that listed default list DEFAULT, and SchemaTenantAssociationLayoutSpec has the row for the uppercase named list, which starts.
…ema check The check refused a MultiTenant owner pointing at a target that the binder does map: a collection that a class-level type registration binds as a basic value, a target that a Hibernate XML mapping resource maps on every connection, and, with no tenant at startup, a target in the hierarchy of the owner, which the binder maps through its root. The remedy in the message and the guide spelled the default connection in lowercase, but the names are case-sensitive. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A valid association is still rejected when no tenant exists at startup.
| */ | ||
| private static boolean isMappedWhereOwnerIs(PersistentEntity owner, PersistentEntity target, Collection<String> tenantSchemaNames) { | ||
| if (tenantSchemaNames == null || tenantSchemaNames.isEmpty()) { | ||
| return target.isMultiTenant() || ConnectionSourcesSupport.getConnectionSourceNames(target).contains(ConnectionSource.ALL) || isMappedByJpaAnnotation(target) || |
There was a problem hiding this comment.
No tenant exists at startup. The target is mapped on the default connection and on the tenant that is added later. Startup should continue. It fails, because this does not treat those named connections as mapped. This commit changes this line and still rejects the association. Keep it.
jdaugherty
left a comment
There was a problem hiding this comment.
The latest commit addresses the class/default serialized-collection registrations, the empty-resolver ancestor case, and the case-sensitive DEFAULT remedy from my previous review. It also recognizes the unprefixed HBM resource covered by the new fixture. One XML compatibility gap remains.
P2 — Recognize namespace-qualified HBM mappings. In HibernateXmlMappings.java:90–107, getElementsByTagName("class") matches a qualified element name, so it does not find <h:class>. Consider the namespace-qualified equivalent of the existing valid HBM fixture, with every mapping element prefixed by h and xmlns:h="http://www.hibernate.org/xsd/orm/hbm", supplied through hibernate.mappingLocations. With a MultiTenant owner referencing that plain target, the new scanner returns no mapped class and the startup check rejects the association.
Hibernate 5.6.15 supports this namespace and processes element local names: see its HbmEventReader and MappingXsdSupport. The diagnostic therefore disagrees with the mapping Hibernate loads.
Please parse namespace-aware and recognize local names in the supported HBM namespaces. Extend the public datastore startup regression with a prefixed resource, both with a known tenant and with an empty resolver followed by tenant creation. This follow-up is based on source inspection; I have not rerun the tests.
…check with their namespaces A mapping resource whose elements carry a prefix, as in <h:class> with xmlns:h set to the Hibernate mapping namespace, is a mapping Hibernate loads, but the scan matched the qualified names and found no class, so the startup check refused an association to a class that such a resource maps. The scan is namespace-aware and reads the local names of the elements of the Hibernate mapping namespaces, and of a mapping with no namespace. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
Fixed in 09db3b2: the scan of the Hibernate XML mapping resources is namespace-aware and reads the local names of the elements of the Hibernate mapping namespaces (
James, for "a valid association is still rejected when no tenant exists at startup": the cases the spec covers with an empty resolver are an owner pointing at a default-only root of its own hierarchy (starts, and tenants can be added), a target mapped by an XML resource (plain and prefixed), a collection bound as a serialized basic value, and a target that is a JPA entity; a default-only entity outside the hierarchy is still refused, as it should be. If your case is another mapping, tell me which and I will add the row. |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A valid mapping is still rejected at startup, including a target mapped in XML and an association the owner's mapping does not use.
| for (int i = 0; i < found.getLength(); i++) { | ||
| Element mapped = (Element) found.item(i); | ||
| String namespace = mapped.getNamespaceURI(); | ||
| if (namespace != null && !HBM_NAMESPACES.contains(namespace)) { |
There was a problem hiding this comment.
A target is mapped in an XML file that names entities, not the older class element. Startup should continue. It fails, because this only reads the older element. Read that file, or do not reject the target.
| continue; | ||
| } | ||
| PersistentEntity target = ((Association<?>) property).getAssociatedEntity(); | ||
| if (target != null && !xmlMappedClasses.contains(target.getJavaClass().getName()) && !isMappedWhereOwnerIs(entity, target, tenantSchemaNames)) { |
There was a problem hiding this comment.
The owner's mapping is in XML and does not include an association. Startup should continue. It fails, because this still checks the association the mapping does not use. Check the mapping that is used.
| */ | ||
| private static boolean isMappedWhereOwnerIs(PersistentEntity owner, PersistentEntity target, Collection<String> tenantSchemaNames) { | ||
| if (tenantSchemaNames == null || tenantSchemaNames.isEmpty()) { | ||
| return target.isMultiTenant() || ConnectionSourcesSupport.getConnectionSourceNames(target).contains(ConnectionSource.ALL) || isMappedByJpaAnnotation(target) || |
There was a problem hiding this comment.
No tenant exists at startup. The target is mapped on the default connection and on the tenant that is added later. Startup should continue. It fails, because this does not treat those named connections as mapped. Keep the association.
…ps, and accept a default plus named target with no tenant The startup check of an association from a multi tenant entity to an entity that a tenant schema does not map refused three layouts that start. A target that a JPA orm.xml maps is read from the entity element and its class attribute, in full or relative to the package element, as a class element of a Hibernate mapping is. An owner that an XML mapping resource maps has the associations the resource names, not the ones of its GORM class, so its associations are not checked. With no tenant at startup, a target that uses the default connection and lists a named one is accepted, as the named connection can be the schema of a tenant added later; a target of the default connection only is still refused. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
A target mapped in an XML file that names entities ( An owner that an XML file maps ( A target on the default connection and a tenant added later ( One more case showed up while building the rows and is not changed here: a target that lists a named connection and not the default makes Hibernate fail with its own The Hibernate 5 core module passes (1422 tests on this branch) and |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A namespace-free ORM document crashes startup, and a valid association is rejected when no tenants exist.
| } | ||
| NodeList found = root.getElementsByTagNameNS("*", "entity"); | ||
| for (int i = 0; i < found.getLength(); i++) { | ||
| Element mapped = (Element) found.item(i); |
There was a problem hiding this comment.
An orm.xml whose entity-mappings element has no namespace is accepted by Hibernate. This check passes null to Set.of().contains and throws NullPointerException, so the application no longer starts. Treat a missing namespace as the document Hibernate already accepts.
| * each connection that maps the owner, are known to be mapped. | ||
| */ | ||
| private static boolean isMappedWhereOwnerIs(PersistentEntity owner, PersistentEntity target, Collection<String> tenantSchemaNames) { | ||
| if (tenantSchemaNames == null || tenantSchemaNames.isEmpty()) { |
There was a problem hiding this comment.
When the tenant resolver returns no tenants, a multi-tenant subclass of a default-only root can reference another default-only entity. The binder maps that hierarchy only on the default connection, where the target exists. This check rejects the association. Allow it when the owner is not mapped on a tenant connection.
…at only the default connection maps An entity-mappings element without a namespace is read by Hibernate, and the check of the XML mapping resources passed its null namespace to an immutable set, which throws, so an application with such a resource no longer started. A missing namespace is now read as the document Hibernate accepts. With no tenant at startup, a multi tenant subclass of a root that only the default connection maps can point at an entity of the default connection, as the binder maps that hierarchy on the default connection only, where the target exists. SchemaTenantAssociationCompatSpec gains the namespace forms of an orm.xml and four shapes of owner hierarchy with the tenant schemas known and with none, 12 rows; 3 of them fail with the previous sources.
|
Pushed the next commit, which answers the review of 12-05 at bdea092. Both findings were regressions against 7.0.x of the startup check this pull request adds: an application that started there no longer started.
|
🚨 All tests passed but jobs failed 🚨Failed Jobs without Test Failures❌ CI - Groovy Joint Validation Build / build_grails 🏷️ Commit: c47e681 Rerun ControlsClick the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A namespace-free ORM document no longer crashes startup. A mapping registered by a custom configuration is still treated as absent, and a stream that can be read only once is opened again.
| * is configured, which this class does not read, so that a caller cannot tell which classes are mapped | ||
| */ | ||
| static Set<String> mappedClassNames(HibernateConnectionSourceSettings.HibernateSettings settings) { | ||
| if (isConfigured(settings.getConfigLocations()) || isConfigured(settings.getMappingJarLocations()) || |
There was a problem hiding this comment.
A custom configuration that registers XML mappings in its constructor, rather than through mappingLocations, loads those mappings on every connection. This method returns an empty set, so a valid association to that target prevents startup. Treat a custom configuration as an unknown mapping source, the same way a config file is treated.
| if (resources == null) { | ||
| return; | ||
| } | ||
| for (Resource resource : resources) { |
There was a problem hiding this comment.
An InputStreamResource in mappingLocations is read once when the default connection is built. This second open throws IllegalStateException, so an application with no tenants at startup no longer starts. Read the names during the first load, or treat a stream that cannot be opened again as unknown.

Replaces #17056, which was based on 7.2.x. The problem is also on 7.0.x, the oldest branch with it, so the change is rebuilt there. The review history is on #17056.
With
grails.gorm.multiTenancy.mode: SCHEMA, each tenant schema gets its own SessionFactory, which maps theMultiTenantentities and the entities whose mapping uses that schema. An association from aMultiTenantentity to an entity that a tenant schema does not map failed at startup with a "refers to an unmapped class" error that does not say why.Change:
HibernateDatastorefinds these associations in private code, so the patch line gets no new public method, and throws aConfigurationExceptionthat names eachOwner.property -> Targetand says how to map the target or to use theDISCRIMINATORmode. It does not add support for such associations.Different from #17056
AllTenantsResolverthat returns no tenant at startup, an association from aMultiTenantentity to anotherMultiTenantentity is accepted, as sbglasius asked: a tenant added later maps both. It was refused before this change.MultiTenanttarget that excludes a schema.Behavior to weigh
I ran these on unchanged 7.0.x and on this branch (H2):
MultiTenanttoMultiTenantMultiTenantto a plain entitySystemPropertyTenantResolverMappingException). Now: refused with the new messageAllTenantsResolver, no tenant at startupMappingException. Now: refused at startupAllTenantsResolver, one tenantThe one changed row is an application that starts without a tenant and never adds one. With
datasource 'ALL'on the target it starts, and the 7.0.18 upgrade note says so.Branch policy: this adds a startup refusal. A MultiTenant association to an entity no tenant schema maps fails at startup on 7.0.x with a MappingException; the one layout that started there, no tenant at startup with a plain target, fails when a tenant is added, and the upgrade note and description say so.
Tests
SchemaTenantAssociationSpecandSchemaTenantAssociationLayoutSpec: 8 of their 24 tests fail on unchanged 7.0.x.grails-data-hibernate5-core: 1397 tests, 59 skipped, none failing.codeStylepasses.Not covered
Two layouts of the 8.0.x spec are left out: a target that lists the default connection and a tenant schema by name, with the tenant schemas known. On 7.0.x the tenant session factories map such a target differently and still fail with the Hibernate
MappingException, which this pull request does not change. The Hibernate 7 half stays on #16850 against 8.0.x.Part of #14345: the application still fails at startup, now with a message that names the associations.
https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
Also accepted since 4b76caa (review of jdaugherty): a collection that a class-level type registration binds as a basic value, a target that a Hibernate XML mapping resource maps on every connection (when a configuration file, a jar or a directory of mappings is configured, which are not read, every target is taken as mapped), and, with no tenant at startup, a target in the hierarchy of the owner. The guide and the message spell the default connection
DEFAULT.Branch policy: the throw in HibernateDatastore is the fail-fast check of this pull request; the one in HibernateXmlMappings only reports a mapping resource that Hibernate cannot load either.