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
}
@Override
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;
@Component
public class MySpringComponent {
@Inject
private HibernateEntityManagerFactory hibernateEntityManagerFactory;
@PostConstruct
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 :)
Your gist has saved an otherwise very frustrating afternoon. Thank you!
As of Hibernate 5, Envers listeners expect an
EnversService
, you can get it just like theEventListenerRegistry
: