Reputation: 234
We are developing a multi tenancy web application using Spring boot + Spring data JPA with hibernate.
Multi tenancy is achieved by having an Organization table, which is wired to almost every table as a foreign key. Which means every DB call (Spring Data repository query methods) will have to be checked with the organization id.
I need a way that, this "where organization_id = ?" check to be injected automatically for every query method. So that developers won't have to specifically bother about organization id checks.
Is this achievable from Spring Data JPA framework? What are the pros, cons of this approach?
Thanks for your time.
Upvotes: 4
Views: 1436
Reputation: 1405
If your have a base class, say BaseEntity you can use @org.hibernate.annotations.Filter:
In BaseEntity:
@FilterDef(name = "organizationFilter", parameters = @ParamDef( name="orgId", type="long" )) @Filter(name = "organizationFilter", condition = "lang_id=:orgId")
On initialization of a session (override JpaTransactionManager.createEntityManagerForTransaction()?):
session.enableFilter("organizationFilter").setParameter("orgId", organization.getId());
Upvotes: 1