Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to config "hibernate.integrator_provider" with springboot 1.5.x

I'm using springboot 1.5.x and trying to implement an event listener following this tutorial.

The blocker I encountered is that I can not set hibernate integrator with SpringBoot 1.5.x。 I have tried to config the integrator in properties.yml like the code below, but it throws an exception that can't cast string to Integrator:

spring:
  jpa:
    properties:
      hibernate.integrator_provider: com.xxxxx.RootAwareEventListenerIntegrator

Here is a related question, But the solution provided not working for springBoot 1.5.x.

like image 454
hsc Avatar asked Mar 05 '23 04:03

hsc


1 Answers

I found a solution usable from here. It doesn't use integrator but add all the event listeners one by one. Below is my code:

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

    }
}
like image 108
hsc Avatar answered May 14 '23 17:05

hsc