Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Register a Hibernate Envers EventListener in Spring Boot (Hibernate 4, Hibernate 5)

Hibernate 4 introduced a new Audit API for event listening.
org.hibernate.envers.event.AuditEventListener was replaced by org.hibernate.event.spi.*, for example org.hibernate.event.spi.PostDeleteEventListener.

First create your custom listener. Example: You want do disable auditing for delete operations.

import org.hibernate.envers.event.spi.EnversPostDeleteEventListenerImpl;
import org.hibernate.event.spi.PostDeleteEvent;

public class MyAuditListener extends EnversPostDeleteEventListenerImpl {

    public MyAuditListener() {
        super(null); //org.hibernate.envers.configuration.spi.AuditConfiguration goes here, but no neccessary, when doing nothing in onPostDelete 

    public void onPostDelete(PostDeleteEvent event) {
        //do not audit delete

Then you have to register your new listener in a spring component, or your @SpringBootApplication annotated class:

import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.PostDeleteEventListener;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.stereotype.Component;

public class MySpringComponent {

	private HibernateEntityManagerFactory hibernateEntityManagerFactory;
	public void registerEnversListeners() {
		EventListenerRegistry listenerRegistry = ((SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory()).getServiceRegistry().getService(EventListenerRegistry.class);
		listenerRegistry.setListeners(EventType.POST_DELETE, new PostDeleteEventListener[]{new MyAuditListener()});

That will work for "doing nothing" EventListeners. For other use cases, you'll have to insert org.hibernate.envers.configuration.spi.AuditConfiguration at the "super" call in the code above.
If you know, how to get the AuditConfiguration, leave a comment :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment