您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

添加一个同时也是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;
        }
    };
}
Java 2022/1/1 18:19:42 有296人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶