Skip to content

Filter a multi-tenant class by the column its tenant id is mapped to (Hibernate 7) - #17253

Open
hk2166 wants to merge 2 commits into
apache:8.0.xfrom
hk2166:fix/tenant-id-column-filter-h7-8.0.x
Open

hk2166 wants to merge 2 commits into
apache:8.0.xfrom
hk2166:fix/tenant-id-column-filter-h7-8.0.x

Conversation

@hk2166

@hk2166 hk2166 commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

The Hibernate 7 counterpart of #17236. In discriminator mode, GORM for Hibernate 7 filters every query of a multi-tenant class by the tenant id. The filter compared the default column of the tenant id property, not the column the mapping gives it. With

static mapping = {
    tenantId name: 'firmId'
    firmId column: 'ledger_firm'
}

the table has a ledger_firm column, but the filter reads firm_id, so every query of the class fails with Column "FIRM_ID" not found. The same goes for a subclass of such a class, and for a collection whose elements are such a class, with or without a join table.

GrailsHibernatePersistentEntity.getMultiTenantFilterCondition now takes the column the mapping gives the tenant id, and the default column only when the mapping sets none. That is the column the binder binds the property to: for a property with no path and no column configuration, ColumnNameForPropertyAndPathFetcher resolves the same mapped column, falling back to the same default. The entity, subclass and collection filters all build their condition through this method. No signature changes.

A subclass's own column mapping of an inherited tenant id creates no column: in every inheritance mode, a property a subclass inherits is bound once, on the root, from the root's mapping. So the condition takes the column of the property the root declares under the tenant id's name, and the entity's own tenant id when the root has no such property. Without that, the filter of a collection whose elements are of a subclass that maps a column of its own named a column that does not exist.

Not covered

  • A collection whose elements are of a joined subclass (tablePerHierarchy false). Hibernate applies the collection filter to the subclass's own table, while the tenant id column is in the root's table, so it fails with an unknown column whatever column the filter names, as it does on 8.0.x. Hibernate 7 throws a NullPointerException for a collection filter with alias maps, so naming the root's table that way does not work. Left for a separate change.

Relates to #14365 and #17236.

Tests

  • MultiTenancyTenantIdColumnSpec (new, grails-data-hibernate7-core, the same spec as in Filter a multi-tenant class by the column its tenant id is mapped to #17236): a query of the class, of a subclass, and of a class with only tenantId name: returns the current tenant's instances only, and none under a tenant that has none. A collection of such elements, through a foreign key, a criteria join and a join table, holds the current tenant's elements only. On 8.0.x without the change, the 5 cases whose tenant id has a column of its own fail with Column "FIRM_ID" not found, and the one for tenantId name: alone passes. With the change, all 6 pass.
  • MultiTenancyTenantIdColumnSpec also has a subclass that maps a tenant id column of its own, with one table, with tablePerHierarchy false and with tablePerConcreteClass true: listing it is filtered by the root's column in all three, and its collections hold only the current tenant's elements with one table and with a table per class. A collection of a subclass whose root isn't multi-tenant but declares the property it takes as its tenant id is covered too. On 1cfdec1, the 3 collection features fail with an unknown column; the listing features pass there as well.
  • GrailsHibernatePersistentEntitySpec: the unit features of getMultiTenantFilterCondition cover a mapping that gives the tenant id a column and one that does not, and a subclass whose root declares the tenant id property and one whose root does not.

Verification

  • On f6f15f9, all 4,716 tests of grails-data-hibernate7-core pass (20 skipped).
  • ./gradlew cleanViolationReports aggregateViolations --continue reports no Checkstyle, CodeNarc, PMD or repository convention violations. SpotBugs is disabled.
  • ./gradlew :grails-data-hibernate7-core:codeStyle is clean.

Generative AI tooling (Claude Code) was used to research the cause, write the change and its tests, and run the checks. I reviewed the change.

Contributor Checklist

Please review the following checklist before submitting your pull request. Pull requests that do not meet these requirements may be closed without review.

Issue and Scope

Code Quality

  • I have added or updated tests that cover the changes introduced in this PR. All code contributions are expected to include appropriate test coverage.
  • I have verified that all existing tests pass by running ./gradlew build --rerun-tasks. (The tests of grails-data-hibernate7-core.)
  • My code follows the project's code style guidelines. I have run ./gradlew codeStyle and resolved any violations. See Code Style for details.
  • This PR does not include mass reformatting, style-only changes, or large-scale refactoring unless it was explicitly approved in the linked issue. Unsolicited reformatting will not be accepted.
  • If generative AI tooling was used in preparing this contribution, a quality model was used to ensure contributions are consistent with the project's quality standards.

Licensing and Attribution

Documentation

  • If this PR introduces user-facing changes, I have included or updated the relevant documentation. (A bug fix; no docs change.)
  • If this PR adds a new feature, I have updated the What's New section of the Grails Guide. (No new feature.)
  • If this PR introduces breaking changes or changes that require user action during an upgrade, I have updated the Upgrade Notes for the corresponding version in the Grails Guide. (No behaviour change.)
  • The PR description clearly explains what was changed and why.

First-time contributors: Please read our Contributing Guide before submitting.
Pull requests that appear to be auto-generated, incomplete, or unrelated to an approved issue may be
closed to help maintainers focus on reviewed and planned work. We appreciate your understanding.

…(Hibernate 7)

In discriminator mode, GORM for Hibernate 7 filters the queries of a
multi-tenant class by its tenant id. The filter compared the default
column of the tenant id property, so with tenantId name: 'firmId' and
firmId column: 'x', every query of the class, of its subclasses, and of a
collection of it failed with an unknown column. The filter now takes the
column the mapping gives the property, which the binder binds it to, and
the default one when the mapping sets none.

The Hibernate 7 counterpart of apache#17236.

See apache#14365
Copilot AI balanced review requested due to automatic review settings December 1, 2026 09:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@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 subclass is filtered by a column that is not the one it maps.

return Optional.ofNullable(getHibernateTenantId())
.map(fetcher::getDefaultColumnName)
.map(defaultColumnName -> ":tenantId = " + defaultColumnName)
.map(tenantId -> Optional.ofNullable(tenantId.getColumnName(null))

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 subclass maps its tenant id to sub_firm. Listing it should use that column. It uses ledger_firm, because the subclass keeps the parent filter. Use the subclass column.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I checked what a subclass's firmId column: 'sub_firm' does, and it creates no sub_firm column. A property a subclass inherits is bound once, on the root, from the root's mapping. That holds with one table, with tablePerHierarchy false, and with tablePerConcreteClass true, where the subclass's own table copies the root's column. So listing the subclass already reads the right column: its rows are filtered by the root's filter on ledger_firm, and that's the column the tenant id is written to.

Where the override did break something is the case @sbglasius points to. The filter of a collection whose elements are of that subclass was built from the subclass's own mapping, and named sub_firm, which doesn't exist. In f6f15f9, the filter condition takes the column of the property the root declares under the tenant id's name, so the collection filter names ledger_firm too. MultiTenancyTenantIdColumnSpec now has a subclass that maps a column of its own in each inheritance mode. Listing it is filtered by the root's column in all three, and a collection of it holds only the current tenant's elements with one table and with a table per class. The collection features fail on 1cfdec1 with Column "SUB_FIRM" not found and Column "UNION_SUB_FIRM" not found.

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

This is an AI assisted review

The fix looks right for the class, and for a subclass that keeps the parent's tenant column. On James's thread: a subclass doesn't get a filter of its own, and the inherited column is created only on the parent's table, so the parent's filter applies to it. The gap I see is ToManyEntityMultiTenantFilterBinder. It builds the filter from the element's own class, so a subclass that remaps firmId column: would filter its collections on a column that doesn't exist. Could you build the filter from the parent class's tenant id, and add a test with a subclass column override, both with the default single-table setup and with tablePerHierarchy false?

A property a subclass inherits is bound once, on the root, from the
root's mapping, in every inheritance mode, so a subclass's own column
mapping of an inherited tenant id creates no column. The filter of a
collection whose elements are of such a subclass was built from the
subclass's mapping and named a column that does not exist. The filter
condition now takes the column of the property the root declares under
the tenant id's name, and the entity's own tenant id when the root has
no such property.

See apache#14365
@hk2166

hk2166 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @jamesfredley and @sbglasius. f6f15f9 builds the filter of a subclass from the column its root maps:

  • What a subclass override creates: in all three inheritance modes, a subclass's firmId column: creates no column. Every table carries the column the root maps, and the subclass's mapping of an inherited property is never bound. So the column to filter by is the root's.
  • The change: getMultiTenantFilterCondition takes the column of the property the root entity declares under the tenant id's name, and the entity's own tenant id when the root has no such property. That covers a subclass of a multi-tenant root, a subclass whose root isn't multi-tenant but declares the property it takes as its tenant id, and a subclass whose tenant id is a property only it declares.
  • Tests: MultiTenancyTenantIdColumnSpec has a subclass that maps a column of its own with one table, with tablePerHierarchy false and with tablePerConcreteClass true. Listing it is filtered by the root's column in all three, and its collections hold only the current tenant's elements with one table and with a table per class. It also has a collection of a subclass whose root isn't multi-tenant. GrailsHibernatePersistentEntitySpec covers taking the root's property and falling back to the entity's own. On 1cfdec1, the 3 collection features fail with an unknown column; the listing features pass there too, since the root's filter already applied.
  • Not covered: a collection of a joined subclass (tablePerHierarchy false). Hibernate applies the collection filter to the subclass's own table, while the tenant id column is in the root's table, so it fails with an unknown column whatever column the filter names. It fails the same way on 8.0.x with the default name. Naming the root's table through the filter's alias maps (aliasTableMap/aliasEntityMap with auto alias injection off) makes Hibernate 7 throw a NullPointerException for a collection filter, so I've left this case out and would take it up separately, unless you'd rather it be in this PR.

All 4,716 tests of grails-data-hibernate7-core pass, and aggregateViolations reports no Checkstyle, CodeNarc, PMD or repository convention violations.

@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 collection load fails when an intermediate class declares the tenant id, and a bracket-quoted column mapping is sent to the database as written.

// so a tenant id the root declares takes the root's column
HibernatePersistentProperty tenantId = getHibernateTenantId();
HibernatePersistentProperty bound = Optional.ofNullable(tenantId)
.flatMap(own -> Optional.ofNullable(getRootEntity())

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.

In a Base, Middle, Leaf hierarchy, Middle declares the tenant id and Leaf maps firmId column: 'leaf_firm'. The lookup checks the root, then uses the leaf mapping. Loading a collection of Leaf filters on leaf_firm and fails with column not found. Previously it filtered on the column Middle bound. Use the column that was actually bound.

.map(root -> ((GrailsHibernatePersistentEntity) root).getHibernatePropertyByName(own.getName())))
.orElse(tenantId);
return Optional.ofNullable(bound)
.map(property -> Optional.ofNullable(property.getColumnName(null))

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.

On H2, firmId column: '[FIRM_ID]' binds the physical column as a quoted identifier, but the filter emits [FIRM_ID], which H2 rejects. The previous predicate used the bound column name.

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

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants