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

为君一笑 提交于 2019-11-26 21:51:13

问题


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?


回答1:


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

}



回答2:


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

    entityManager.unwrap(Session.class)
            .enableFilter("notDeleted")
            .setParameter("isDeleted", false);


来源:https://stackoverflow.com/questions/32228031/access-to-session-using-spring-jpa-and-hibernate-in-order-to-enable-filters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!