@TenantId filtering when loading by Primary Key

Hello, I’m using Hibernate 6.4.4.Final and CurrentTenantIdentifierResolver to develop a multi-tenant application. I’m not seeing the expected filtering by @TenantId happening when loading entities by their primary key.

For example I get this sql generated for an entity that has a @TenantId column:

["select cb1_0.id,cb1_0.created_by_id,...cb1_0.name,cb1_0.tenant_id 
from carrier cb1_0 where cb1_0.id=?"], Params:[(2)]

I would expect that to have another where tenant_id = ? clause, like the non-primary key queries do. Non-primary key queries do append the where tenant_id = ? clause on as expected, for example:

["select cb1_0.id,cb1_0.created_by_id,...cb1_0.name,cb1_0.tenant_id 
from carrier cb1_0 join carrier_transportation_type cttb1_0 on cttb1_0.tenant_id = ? and cb1_0.id=cttb1_0.carrier_id 
where cb1_0.tenant_id = ? and (? is null or ?=cttb1_0.transportation_type) and (? is null or lower(cb1_0.name) like ? escape '') offset ? rows fetch first ? rows only"], Params:[(1,1,NULL(VARCHAR),NULL(VARCHAR),NULL(VARBINARY),NULL(VARCHAR),0,20)]

I’ve followed the query down into LoaderSelectorBuilder where I see that loadQueryInfluencers is populated with a _tenantId filter. That filter doesn’t seem to be applied the query, and I haven’t made much progress following the code after that.

Is this expected behavior or a bug with the @TenantId system?
Where in the code should the @TenantId filtering be applied for this type of query?

This is a known limitation of the current implementation. You can follow [HHH-16830] - Hibernate JIRA for updates on this topic.

Was this known limitation mentioned somewhere in the docs that I missed?

The general thought process is that, if the caller to Session.find() knows an internal primary key, then it must have gotten it from a secure context i.e. you shouldn’t run Session.find() if you’re unsure that the caller is allowed to access the data. You should rather run a query.

We acknowledge the desire to apply the tenant filter though, which is why HHH-16830 is being discussed.

Can I submit a PR to change the docs for the @TenantId feature to highlight this limitation for other users? I don’t immediately see where the source for this document is hosted: Hibernate ORM User Guide. The docs as they are currently written really make it seem like this should work.

Sure you can, here are the docs. Note though, that we are considering to merge the PR for [HHH-16830] - Hibernate JIRA for the final 6.5 release, so if you want to provide a PR, better provide it against the 6.4 branch.