小编典典

如何在Spring Boot中使用Spring托管的Hibernate拦截器?

spring-boot

是否可以在Spring
Boot中集成Spring托管的Hibernate拦截器(http://docs.jboss.org/hibernate/orm/4.3/manual/en-
US/html/ch14.html)?

我正在使用Spring Data JPA和Spring Data REST,并且需要一个Hibernate拦截器来对实体上的特定字段进行更新。

使用标准的JPA事件,不可能获得旧的值,因此,我认为我需要使用Hibernate拦截器。


阅读 537

收藏
2020-05-30

共1个答案

小编典典

添加一个同时也是Spring
Bean的Hibernate拦截器并没有特别简单的方法,但是如果完全由Hibernate进行管理,则可以轻松添加一个拦截器。为此,将以下内容添加到您的application.properties

spring.jpa.properties.hibernate.ejb.interceptor=my.package.MyInterceptorClassName

如果您还需要Interceptor成为bean,则可以创建自己的LocalContainerEntityManagerFactoryBean。在EntityManagerFactoryBuilder从spring引导1.1.4是有点过于严格,以与一般的属性,所以你需要转换为中(Map),我们将看到固定,对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;
        }
    };
}
2020-05-30