在HandlerInterceptor上启用hibernate过滤器

时间:2016-10-03 07:40:54

标签: java spring hibernate spring-boot

我有这样的休眠过滤器:

@Entity
@FilterDef(name = "filter_name", parameters = { @ParamDef(name = "tenatId", type = "long") })
@Filter(name = "filter_name", condition = "tenant_id = :tenantId")
public class MyEntity {

   private long tenantId;

}

我希望每次请求都启用此过滤器,所以我创建了这样的Request Interceptor:

@Configuration
public class RequestInterceptor implements HandlerInterceptorAdapter {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
        Object handler) throws Exception {
        Filter filter = entityManager.unwrap(Session.class).enableFilter("filter_name");
        filter.setParameter("tenantId", myService.getTentantId());
    }
}

但我不能在事务管理器上得到错误:

java.lang.IllegalStateException: No transactional EntityManager available
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:272)
    at com.sun.proxy.$Proxy184.unwrap(Unknown Source)
    at id.gdplabs.koi.api.config.security.RequestInterceptor.preHandle(RequestInterceptor.java:27)
    at org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter.preHandle(WebRequestHandlerInterceptorAdapter.java:56)
    at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:134)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:958)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
...

如果我将代码移动到控制器,它可以工作:

@RequestMapping(method = RequestMethod.GET, value = "/test")
public List<MyEntity> test() {
    Filter filter = entityManager.unwrap(Session.class).enableFilter("filter_name");
    filter.setParameter("tenantId", myService.getTentantId());
    return myService.findAll();
}

你知道为什么我不能在拦截器中解包hibernate会话吗?

欢迎任何建议,谢谢!

0 个答案:

没有答案