How To Implement Conditional Auditing With Hibernate Envers
How To Implement Conditional Auditing With Hibernate Envers
www.thoughts-on-java.org
Implement Conditional Auditing with Hibernate Envers
I do that in the MyEnversPreUpdateEventListenerImpl class. It
extends Envers’ EnversPreUpdateEventListenerImpl and overrides
the onPreUpdate method.
Within that method, I check if the event was triggered for a Book
entity and if the publishingDate is null. If that’s the case, I ignore the
event and in all other cases, I just call the method on the superclass.
public class MyEnversPreUpdateEventListenerImpl extends
EnversPreUpdateEventListenerImpl {
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
if (event.getEntity() instanceof Book &&
((Book) event.getEntity()).getPublishingDate() == null) {
log.debug("Ignore all books that are not published.");
return false;
}
return super.onPreUpdate(event);
}
}
www.thoughts-on-java.org
Implement Conditional Auditing with Hibernate Envers
@Override
public void onPostUpdate(PostUpdateEvent event) {
if (event.getEntity() instanceof Book &&
((Book) event.getEntity()).getPublishingDate() == null) {
log.debug("Ignore all books that are not published.");
return;
}
super.onPostUpdate(event);
}
}
www.thoughts-on-java.org
Implement Conditional Auditing with Hibernate Envers
Java Callbacks
public class MyEnversIntegrator implements Integrator {
@Override
public void integrate(Metadata metadata,
SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
...
if (enversService.getEntitiesConfigurations()
.hasAuditedEntities()) {
…
listenerRegistry.appendListeners(
EventType.PRE_UPDATE,
new MyEnversPreUpdateEventListenerImpl(
enversService )
);
listenerRegistry.appendListeners(
EventType.POST_UPDATE,
new MyEnversPostUpdateEventListenerImpl(
enversService )
);
}
}
...
}
www.thoughts-on-java.org
Implement Conditional Auditing with Hibernate Envers
The last thing you need to do to use your custom event listeners is to
add the fully qualified name of your Integrator implementation in the
META-INF/services/org.hibernate.integrator.spi.Integrator file.
org.thoughts.on.java.envers.MyEnversIntegrator
OK, that’s all. Hibernate Envers will now use your custom event
listeners.
Learn more
You can learn more about Hibernate Envers in the following posts:
www.thoughts-on-java.org