0

I'm trying to retrieve current entityManager when calling methods from a certain repo. Do you have an idea how I could merge these 2 pointcuts ?

@Pointcut("execution(* com.package.repository.MyRepo.*(..))")
public void insideRepository() {}

@Pointcut("execution(* javax.persistence.EntityManagerFactory+.createEntityManager(..))")
public void createEntityManager() {}

@Before("insideRepository()")
public void enableFilter(JoinPoint jp) {
    System.out.println("Inside repo");
}

@AfterReturning(pointcut = "createEntityManager()", returning = "entityManager")
public void enableFilter(EntityManager entityManager) {
    try {
        entityManager.unwrap(Session.class).enableFilter("myFilter");
    } catch (Exception e) {
        System.out.println("No filter myFilter for this entity");
    }
}

This current solution is working, but I would like to not trigger the catch and call enableFilter only when a method from my repo is called.

Btw, I had to do this tricks because having ...

@PersistenceUnit(unitName = "mySecondDb")
EntityManagerFactory emf;

// OR

@PersistenceContext(unitName = "mySecondDb")
EntityManager em;

... was not working :(

SBDev
  • 1
  • Welcome to SO. An [MCVE](https://stackoverflow.com/help/mcve) instead of just snippets would be great, ideally on GitHub. Then somebody like me who knows AOP, but not Spring or JPA, might be able to help you more effectively. Please also explain what you mean by "merging pointcuts" and why the try-catch block is a problem. – kriegaex Nov 25 '21 at 13:15
  • Hi, and thanks for your answer. I'll try to create a MCVE that can reproduce this problem later ... I think my solution is a problem because of performance problems. Maybe i'm wrong on this point ... let me know. Then, i fill like it's bad code to try to enable a filter that in most of the time doesn't exist for a requested entity. By merging the two pointcuts, I mean retrieve the current entityManager only for a specific repository ... – SBDev Nov 25 '21 at 13:42
  • Hope you had tried to follow the advice in this question before going the AOP route. https://stackoverflow.com/questions/28817120/how-to-inject-multiple-jpa-entitymanager-persistence-units-when-using-spring – Sree Kumar Nov 27 '21 at 05:16

0 Answers0