首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用springboot 1.5.x配置"hibernate.integrator_provider“

如何使用springboot 1.5.x配置"hibernate.integrator_provider“
EN

Stack Overflow用户
提问于 2019-04-10 15:53:52
回答 1查看 1.9K关注 0票数 4

我正在使用Springboot1.5.x,并尝试按照this教程实现一个事件侦听器。

我遇到的阻碍是我不能用SpringBoot 1.5.x设置hibernate integrator。我尝试在properties.yml中配置集成器,如下面的代码所示,但它抛出了一个无法将字符串转换为集成器的异常:

代码语言:javascript
复制
spring:
  jpa:
    properties:
      hibernate.integrator_provider: com.xxxxx.RootAwareEventListenerIntegrator

Here是一个相关问题,但提供的解决方案不适用于springBoot 1.5.x。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-12 14:22:12

我从here找到了一个可用的解决方案。它不使用integrator,而是逐个添加所有的事件监听器。下面是我的代码:

代码语言:javascript
复制
public class RootAwareInsertEventListener implements PersistEventListener {

    public static final RootAwareInsertEventListener INSTANCE = new RootAwareInsertEventListener();

    @Override
    public void onPersist(PersistEvent event) throws HibernateException {
        final Object entity = event.getObject();

        if (entity instanceof RootAware) {
            RootAware rootAware = (RootAware) entity;
            Object root = rootAware.getRoot();
            event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);

            log.info("Incrementing {} entity version because a {} child entity has been inserted",
                    root, entity);
        }
    }

    @Override
    public void onPersist(PersistEvent event, Map createdAlready)
            throws HibernateException {
        onPersist(event);
    }
}
代码语言:javascript
复制
@Component
public class HibernateListenerConfigurer {

    @PersistenceUnit
    private EntityManagerFactory emf;

    @PostConstruct
    protected void init() {
        SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.PERSIST).appendListener(RootAwareInsertEventListener.INSTANCE);
        registry.getEventListenerGroup(EventType.FLUSH_ENTITY).appendListener(RootAwareUpdateAndDeleteEventListener.INSTANCE);

    }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55607443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档