title: Accessing the EntityManager in an @Aspect for a JpaRepository
body: <p>I've been trying to follow the advice from <a href="https://medium.com/@Integral_io/elegant-multi-tenancy-for-microservices-part-iii-implementation-supporting-infrastructure-64b74093615" rel="nofollow noreferrer">1</a>, to implement discriminator column based multi-tenancy using Hibernate interceptors and filters in Spring Boot 2.0.5. So far the Interceptor is working, however I want to apply the Hibernate filter directly on Spring Data JPA Repositories. The aspect I wrote looks like this:</p>
  
  <pre><code>@Aspect
  @Component
  public class TenantAwareRepositoryAspect {
  
      @Autowired
      private EntityManager entityManager;
  
      @Before("execution(* com.example.tenant.jpasupport.TenantAwareRepository+.*(..))")
      public void before(JoinPoint joinPoint){
          entityManager
              .unwrap(Session.class)
              .enableFilter(TENANT_FILTER_NAME)
              .setParameter(TENANT_ID_PROPERTY_NAME, TenantHolder.getTenantId());
      }
  }
  </code></pre>
  
  <p>I then add the <code>TenantAwareRepository</code> as a marker interface to the repositories that contain Tenant-scoped entities.</p>
  
  <p>Now: My tests of the repositories using the @DataJpaTest annotation run through just fine, but when I start the app and try to fetch some data I am getting a <code>IllegalStateException</code> with message <strong>"No transactional EntityManager available"</strong>. I have an <code>@EnableTransactionManagement</code> on my app configuration.</p>
  
  <p>I am guessing I need to access the excact EntityManager that is used in the generated Spring Data Repository, but how do I get that in the aspect?</p>