J4Priyan
J4Priyan

Reputation: 234

Spring Data JPA global filter clause which inherits for all repository methods

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

Answers (1)

Argb32
Argb32

Reputation: 1405

If your have a base class, say BaseEntity you can use @org.hibernate.annotations.Filter:

  1. In BaseEntity:

    @FilterDef(name = "organizationFilter", parameters = @ParamDef( name="orgId", type="long" )) @Filter(name = "organizationFilter", condition = "lang_id=:orgId")

  2. On initialization of a session (override JpaTransactionManager.createEntityManagerForTransaction()?):

    session.enableFilter("organizationFilter").setParameter("orgId", organization.getId());

Upvotes: 1

Related Questions