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

2

10

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?

Selenite answered 26/8, 2015 at 13:29 Comment(0)
S
16

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");
        }
    }

}
Selenite answered 26/8, 2015 at 15:33 Comment(2)
Truly uniform solution. The only shame is that Spring Data design is so bad, that only hacks like this work. As in different parts of Spring, private on finals, and no single point where you can hook with the custom code.Upstairs
Thank you! I used entityManager , but without transaction it can't work.This answer helps me a lot.Graves
F
0

here's one i use for apps that support is_delete on objects -

    entityManager.unwrap(Session.class)
            .enableFilter("notDeleted")
            .setParameter("isDeleted", false);
Fabrianne answered 9/5, 2017 at 3:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.