是否可以多次注册单个Hibernate拦截器?

时间:2018-01-18 07:09:48

标签: java spring hibernate interceptor

问题是我有一个如下所示的Hibernate拦截器:

public class CustomInterceptor extends EmptyInterceptor {

    private String tenant;

    public CustomInterceptor(String tenant) {
        this.tenant = tenant;
    }

   @Override    
   public String onPrepareStatement(String sql) {
        String prepedStatement = super.onPrepareStatement(sql);
        if (tenant != null) {
            prepedStatement = prepedStatement.replaceAll("TABLE_NAME_1", "TABLE_" + tenant);
        }
        return prepedStatement;
    }  }

我可以在启动上面的Interceptor期间进行初始化,但我想要的是能够像Spring Interceptors允许的那样向不同的租户注册相同的拦截器,如下所示:

registry.addInterceptor(new CustomInterceptor("tenant1")).addPathPatterns("/wow/tenant1");

registry.addInterceptor(new CustomInterceptor("tenant2")).addPathPatterns("/wow/tenant2");

registry.addInterceptor(new CustomInterceptor("tenant3")).addPathPatterns("/wow/tenant3");

我无法在Hibernate中执行多个拦截器的这个注册表,因此我不可能使用Spring Interceptor,因为Spring Interceptor在我的情况下不提供Hibernate Interceptor所做的事情(即onPrepareStatement能够更改表名)在运行时间。)

任何人都可以建议如何使用Hibernate注册多个拦截器?我不确定Hibernate是否可行。

编辑:

答案(基于我的研究和实施): 在引导时注册多个拦截器,然后根据传入的请求模式指向不同的拦截器,这是由Spring提供的,Hibernate不支持。

1 个答案:

答案 0 :(得分:0)

您可以引入InterceptorProxy来保留CustomInterceptors列表。

public class InterceptorProxy extends EmptyInterceptor {

    private List<CustomInterceptor> interceptors;

    public InterceptorProxy (List<CustomInterceptor>) {
        this.interceptors = interceptors;
    }

   @Override    
   public String onPrepareStatement(String sql) {
        String prepedStatement = super.onPrepareStatement(sql);
        for (CustomInterceptor ci:interceptors) {
             //your logic here
        }
        return prepedStatement;
    }  
}