Skip to content

fix(hibernate5): fail fast when a SCHEMA multi-tenant entity references an entity no tenant schema maps - #17276

Open
borinquenkid wants to merge 10 commits into
7.0.xfrom
fix/h5-schema-tenant-association-on-7.0.x
Open

borinquenkid wants to merge 10 commits into
7.0.xfrom
fix/h5-schema-tenant-association-on-7.0.x

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

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 the MultiTenant entities and the entities whose mapping uses that schema. An association from a MultiTenant entity 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: HibernateDatastore finds these associations in private code, so the patch line gets no new public method, and throws a ConfigurationException that names each Owner.property -> Target and says how to map the target or to use the DISCRIMINATOR mode. It does not add support for such associations.

Different from #17056

  • With an AllTenantsResolver that returns no tenant at startup, an association from a MultiTenant entity to another MultiTenant entity is accepted, as sbglasius asked: a tenant added later maps both. It was refused before this change.
  • The message no longer calls the target "not MultiTenant", which is wrong for a MultiTenant target that excludes a schema.

Behavior to weigh

I ran these on unchanged 7.0.x and on this branch (H2):

Resolver MultiTenant to MultiTenant MultiTenant to a plain entity
SystemPropertyTenantResolver starts, a tenant can be added 7.0.x: does not start (MappingException). Now: refused with the new message
AllTenantsResolver, no tenant at startup starts, a tenant can be added 7.0.x: starts, and adding a tenant later throws the MappingException. Now: refused at startup
AllTenantsResolver, one tenant starts, a tenant can be added 7.0.x: does not start. Now: refused with the new message

The 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

  • SchemaTenantAssociationSpec and SchemaTenantAssociationLayoutSpec: 8 of their 24 tests fail on unchanged 7.0.x.
  • grails-data-hibernate5-core: 1397 tests, 59 skipped, none failing. codeStyle passes.

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.

… 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
…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

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.

🟡 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

Comment on lines +743 to +747
if (!(property instanceof Association) || property instanceof Embedded || property instanceof EmbeddedCollection) {
continue;
}
PersistentEntity target = ((Association<?>) property).getAssociatedEntity();
if (target != null && !isMappedWhereOwnerIs(entity, target, tenantSchemaNames)) {

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.

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:

  1. A property declared with a domain type but bound as a basic value (a custom UserType, or type: 'serializable' on a hasMany) is left out of the check, as GrailsDomainBinder binds it as a SimpleValue.
  2. A subclass of a root that excludes the schema is checked against the connection sources of every ancestor, since TenantDataSourceConfig is not inherited and the binder maps a subclass only through its root.
  3. 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)) {

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.

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:

  1. A property declared with a domain type but bound as a basic value (a custom UserType, or type: 'serializable' on a hasMany) is left out of the check, as GrailsDomainBinder binds it as a SimpleValue.
  2. A subclass of a root that excludes the schema is checked against the connection sources of every ancestor, since TenantDataSourceConfig is not inherited and the binder maps a subclass only through its root.
  3. 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));

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.

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:

  1. A property declared with a domain type but bound as a basic value (a custom UserType, or type: 'serializable' on a hasMany) is left out of the check, as GrailsDomainBinder binds it as a SimpleValue.
  2. A subclass of a root that excludes the schema is checked against the connection sources of every ancestor, since TenantDataSourceConfig is not inherited and the binder maps a subclass only through its root.
  3. 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 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 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);

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.

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.

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.

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

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.

Comment on lines +803 to +805
Object type = mappedForm instanceof PropertyConfig ? ((PropertyConfig) mappedForm).getType() : null;
if (type == null) {
return 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.

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

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.

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);

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.

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

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.

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);

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.

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

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.

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.

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.

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

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.

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 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 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) ||

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.

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

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

Copy link
Copy Markdown
Member Author

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 (http://www.hibernate.org/xsd/orm/hbm and http://www.hibernate.org/xsd/hibernate-mapping), and of a mapping that has no namespace, so <h:class> with xmlns:h set is found, with the package of the root applied. An element of another namespace is not read as a class.

SchemaTenantAssociationCompatSpec has a prefixed resource (CompatPrefixedXmlTarget.hbm.xml, every mapping element prefixed by h) supplied through hibernate.mappingLocations, and the owner starts both with the tenant schemas known and with an empty resolver followed by addTenantForSchema('tenant1'). With the earlier scanner put back, both rows fail. The Hibernate 5 module passes (1412 tests) and codeStyle passes.

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 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 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)) {

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 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)) {

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 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) ||

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.

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

Copy link
Copy Markdown
Member Author

bdea092c789 takes the three findings.

A target mapped in an XML file that names entities (HibernateXmlMappings.java:112). A JPA orm.xml is read now: an entity element names its class in the class attribute, in full or relative to the package element, in the three orm namespaces. Rows: a target in an orm.xml with a package element, and one with the class named in full, each with the tenant schemas known and with no tenant at startup.

An owner that an XML file maps (HibernateDatastore.java:758). An owner that an XML mapping resource maps, a Hibernate mapping or an orm.xml, has the associations that the resource names, so its associations are no longer checked against its GORM class. Rows: an owner in each kind of file whose mapping leaves out the association its GORM class declares, each with the tenant schemas known and with no tenant at startup.

A target on the default connection and a tenant added later (:777). With no tenant at startup, a target that uses the default connection and lists a named connection is accepted, because the named connection can be the schema of a tenant added later. A target of the default connection only is still refused, and the existing row for it passes. The row for the accepted layout starts with a configured tenant1 data source and no tenant.

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 MappingException, before this check runs.

The Hibernate 5 core module passes (1422 tests on this branch) and codeStyle passes. With the two main files put back, the 9 new rows fail.

@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 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);

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 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()) {

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.

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

Copy link
Copy Markdown
Member Author

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.

  • An orm.xml whose entity-mappings element has no namespace. Hibernate reads it. The check of the XML mapping resources passed the null namespace to an immutable Set, which throws NullPointerException, so the application did not start. A missing namespace is now read as the document Hibernate accepts. The two namespaces of a JPA orm.xml that were handled before, and the legacy one (java.sun.com), are rows next to it.
  • No tenant at startup, a multi tenant subclass of a root that only the default connection maps. The binder maps that hierarchy on the default connection only, so the target exists where the owner is mapped; the check refused it. With no tenant names to check, an owner whose root is not multi tenant and lists no connection but the default is now taken as mapped on the default connection only, and its target needs to be mapped there only.

SchemaTenantAssociationCompatSpec has the table: the namespace forms of an orm.xml (qualified, legacy, none), and four shapes of owner hierarchy (maps only the default connection to an entity of the default connection, the same to a multi tenant entity, maps every connection, has a multi tenant root), each with the tenant schemas known and with none, 12 rows in all. The shapes that must still be refused are rows too. With the sources of the previous commit 3 rows fail (both namespace-free rows, and the default-only owner with no tenant at startup).

grails-data-hibernate5-core passes (1434 tests) and codeStyle is clean.

@testlens-app

testlens-app Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

🚨 All tests passed but jobs failed 🚨

Failed Jobs without Test Failures

❌ CI - Groovy Joint Validation Build / build_grails
❌ CI / Hibernate5 Functional Tests (17)
❌ CI / Hibernate5 Functional Tests (25)

🏷️ Commit: c47e681
▶️ Tests: 61196 executed
⚪️ Checks: 58/58 completed

Rerun Controls

Click the checkbox to trigger a rerun:

  • Rerun jobs

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 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()) ||

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 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) {

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

This branch has not been deployed

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

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants