如何在 Spring Boot 中使用 Spring 管理的 Hibernate 拦截器? [英] How to use Spring managed Hibernate interceptors in Spring Boot?
问题描述
是否可以集成 Spring 管理的 Hibernate 拦截器(http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch14.html) 在 Spring Boot 中?
Is it possible to integrate Spring managed Hibernate interceptors (http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch14.html) in Spring Boot?
我正在使用 Spring Data JPA 和 Spring Data REST,并且需要一个 Hibernate 拦截器来处理实体上特定字段的更新.
I'm using Spring Data JPA and Spring Data REST and need an Hibernate interceptor to act on an update of a particular field on an entity.
使用标准 JPA 事件不可能获得旧值,因此我认为我需要使用 Hibernate 拦截器.
With standard JPA events it's not possible to get the old values, and hence I think I need to use the Hibernate interceptor.
推荐答案
添加一个也是 Spring Bean 的 Hibernate 拦截器并没有特别简单的方法,但是如果它完全由 Hibernate 管理,您可以轻松添加一个拦截器.为此,请将以下内容添加到您的 application.properties
:
There's not a particularly easy way to add a Hibernate interceptor that is also a Spring Bean but you can easily add an interceptor if it's managed entirely by Hibernate. To do that add the following to your application.properties
:
spring.jpa.properties.hibernate.ejb.interceptor=my.package.MyInterceptorClassName
如果您需要拦截器也是一个 bean,您可以创建自己的 LocalContainerEntityManagerFactoryBean
.Spring Boot 1.1.4 中的 EntityManagerFactoryBuilder
对属性的泛型有点过于严格,所以你需要转换为 (Map)
,我们将考虑修复它1.2.
If you need the Interceptor to also be a bean you can create your own LocalContainerEntityManagerFactoryBean
. The EntityManagerFactoryBuilder
from Spring Boot 1.1.4 is a little too restrictive with the generic of the properties so you need cast to (Map)
, we'll look at fixing that for 1.2.
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder factory, DataSource dataSource,
JpaProperties properties) {
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.putAll(properties.getHibernateProperties(dataSource));
jpaProperties.put("hibernate.ejb.interceptor", hibernateInterceptor());
return factory.dataSource(dataSource).packages("sample.data.jpa")
.properties((Map) jpaProperties).build();
}
@Bean
public EmptyInterceptor hibernateInterceptor() {
return new EmptyInterceptor() {
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
System.out.println("Loaded " + id);
return false;
}
};
}
这篇关于如何在 Spring Boot 中使用 Spring 管理的 Hibernate 拦截器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!