title: How to enable Multitenancy with Spring Data Jpa
body: <p><strong>Background :</strong> I am building a Multitenant SaaS app and have chosen single database, shared schema as the Multitenancy approach. Every table has a discriminator column "tenantId" to isolate the tenant data. I am using spring boot as the application framework and leveraging spring data jpa for the data layer with Hibernate as the JPA provider. I really like the way spring data helps in eliminating boilerplate code and have currently coded the respositories like below,</p>
  
  <pre><code>@Repository
  public interface UserRepository extends JpaRepository&lt;User,Long&gt;{
  
  }
  </code></pre>
  
  <p>and services like below,</p>
  
  <pre><code>public class UserService{
      @Autowired
      private UserRepository userRepo;
      public User getUser(){
          User user = userRepo.findOne(id);
      }
  }
  </code></pre>
  
  <p><strong>Problem Statement:</strong> When i want to get user, i want to get the user for a particular org. I am wondering how do i add the tenant criteria, i do not want to write custom repository implementations as that will introduce boilerplate code.</p>
  
  <p><strong>Solutions Attempted:</strong></p>
  
  <p>i) Hibernate Interceptor - onPrepareStatememt : This is not useful as the sql is a string and i do not want to do string manipulation.</p>
  
  <p>ii)Enabling Hibernate Filters with Spring AOP: Annotated entity with @Filter and tried setting the filter in session. This does not work as the aspect is never invoked.</p>
  
  <pre><code>@AfterReturning(pointcut = "execution(* org.hibernate.jpa.internal.EntityManagerImpl.OpenSession(..))", returning = "session")
  public void forceFilter(JoinPoint joinPoint, Object session) {
  
      Session hibernateSession = (Session) session;
      session.enableFilter("tenantFilter")
  }
  </code></pre>
  
  <p>The hibernate filters sounds like a promising approach but i have kind of hit the wall trying to put in a working solution. I would like to know if there is an alternate approach to enable the hibernate filter in the session that Spring data uses internally to query the data.</p>