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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With