Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to Session using Spring JPA and Hibernate in order to enable filters

In a Spring JPA + Hibernate environment I need to enable Hibernate entity filters. So I should have access to Hibernate Session object, but I'm using EntityManagerFactory and Spring JPA magics. There is any Session interceptor so I can call the enableFilters() method on it every time Spring create a new Session?

like image 243
lincetto Avatar asked Aug 26 '15 13:08

lincetto


1 Answers

I ended up with AOP solution :

@Aspect
@Component
public class EnableFilterAspect {

    @AfterReturning(
            pointcut="bean(entityManagerFactory) && execution(* createEntityManager(..))",
            returning="retVal")
    public void getSessionAfter(JoinPoint joinPoint, Object retVal) {
        if (retVal != null && EntityManager.class.isInstance(retVal)) {
            Session session = ((EntityManager) retVal).unwrap(Session.class);
            session.enableFilter("myFilter").setParameter("myParameter", "myValue");
        }
    }

}
like image 64
lincetto Avatar answered Sep 18 '22 12:09

lincetto