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

时间:2019-04-10 07:53:52

标签: hibernate spring-boot jpa

我正在使用springboot 1.5.x,并尝试按照this教程实施事件监听器。

我遇到的阻止者是我无法使用SpringBoot 1.5.x设置休眠集成器。我试图像下面的代码那样在properties.yml中配置集成器,但是它抛出了无法转换字符串的异常集成商:

spring:
  jpa:
    properties:
      hibernate.integrator_provider: com.lenovo.sci.smartbms.events.RootAwareEventListenerIntegrator

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

1 个答案:

答案 0 :(得分:1)

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

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);
    }
}
@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);

    }
}