Search code examples
hibernatespring-data-jpaspring-data

How to create a dynamic WHERE clause for all queries in Spring Data JPA?


I have a requirement where I need to pass a global WHERE condition dynamically to all the queries?

We have data in the tables for multiple organizations. So, I need to pass ORG_ID = ? while retrieving data.

I don't want to write finder methods like findBy..AndOrgId(... Integer orgId). Is there a better way to do this? To apply a Global WHERE clause or a Predicate?

I receive this orgId as part of the request attribute in RestController. Since it is dynamic, I can't use the hibernate annotation @Where on the entity classes.


Solution

  • Spring Data (I assume you are using Spring Data based on your post tags) doesn't support query augmentation (at time of writing). There is a long standing request for that feature here that also describes some alternatives that others have tried.

    Good luck!