[英]How can I activate Hibernate @Filter in Spring boot?
The final goal that I want to achieve is to use some information from the request headers to use on a Hibernate filter .我想要实现的最终目标是使用请求标头中的一些信息在Hibernate 过滤器上使用。
The webapp is a fairly neat Spring boot webapp using Jpa Repositories. webapp 是一个相当简洁的 Spring 使用Jpa Repositories引导 webapp 。
I've configured a filter definition in the model entity and I want to have it activated on the webapp.我在 model 实体中配置了一个过滤器定义,我想在 webapp 上激活它。 I use a request handler:
我使用请求处理程序:
The Entity:实体:
@Entity
@Getter
@Setter
@Table(name = "personas")
@FilterDef(name = "filtro_personas", parameters = @ParamDef(name = "idparam", type = "int"))
public class Persona implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Filter(name = "filtro_personas", condition = ":idparam = id")
private Integer id;
private String nombre;
@OneToMany(mappedBy ="persona")
private List<Wallet> cuentas;
}
The request handler:请求处理程序:
public class LangHeaderInterceptor implements HandlerInterceptor {
private EntityManager entityManager;
public LangHeaderInterceptor( EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
if (entityManager != null ) {
// Sample of use of the filter.at this point the HttpServletRequest and entity manager are filled.
Session s = entityManager.unwrap(Session.class);
s.enableFilter("filtro_personas").setParameter("idparam", 1).;
}
return true;
}
}
The request handler configuration:请求处理程序配置:
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Autowired
private EntityManager entityManager;
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
//System.out.println("TRACING MESSAGE: CUSTOM INTERCEPTOR ADDED");
registry.addInterceptor(new LangHeaderInterceptor(entityManager));
}
}
Hey friend you can't do this in the way you're trying without mixing concerns.嘿,朋友,您不能以您尝试的方式做到这一点,而不会引起关注。 The InterceptorRegistry usage that you try is an odd place to try this (you are not likely to start a transaction before going inside the execution of a controller's methods).
您尝试的 InterceptorRegistry 用法是一个奇怪的地方尝试此操作(您不太可能在进入控制器方法的执行之前启动事务)。
The use that Springboot
makes of Hibernate
and Jpa
's interface makes the actual session on your data access only trully available on the context of an @Transactional
annotation. Springboot
对Hibernate
和Jpa
接口的使用使得实际的 session 在您的数据访问上仅在@Transactional
注释的上下文中真正可用。
You should do an AOP approach to your intent so you catch the transaction/session.您应该对您的意图执行AOP 方法,以便捕获事务/会话。
Some links on the matter:关于此事的一些链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.