其他分享
首页 > 其他分享> > 使用Spring JPA和Hibernate访问Session以启用过滤器

使用Spring JPA和Hibernate访问Session以启用过滤器

作者:互联网

Spring JPA Hibernate环境中,我需要启用Hibernate实体过滤器.
所以我应该有权访问Hibernate Session对象,但我正在使用EntityManagerFactory和Spring JPA魔法.
有任何Session拦截器,所以每次Spring创建一个新Session时我都可以调用enableFilters()方法吗?

解决方法:

我最终得到了AOP解决方案:

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

}

标签:spring,hibernate,spring-orm
来源: https://codeday.me/bug/20190927/1824263.html