如何在 Spring Boot 中使用 Spring 托管的 Hibernate 拦截器? [英] How to use Spring managed Hibernate interceptors in Spring Boot?

查看:47
本文介绍了如何在 Spring Boot 中使用 Spring 托管的 Hibernate 拦截器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以集成 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆