4

I record a history of all changes to some entities and am about to implement a mechanism similar to Envers to take care of this automatically. My question is whether to use Hibernate interceptors or their event system?

It seems like interceptors is a little simpler and does all I need. And Hibernate's own documentation suggests using interceptors for "tracking audit information." But their audit information isn't in a companion table for each entity and Envers uses the event system I imagine for a reason.

I'm using Spring 3.0 and Hibernate 3.5 (latest stables).

UPDATE: database triggers are not desirable for this situation. I'm eager to hear thoughts on hibernate interceptors vs events for audit trails/change histories.

skaffman
  • 398,947
  • 96
  • 818
  • 769
at.
  • 50,922
  • 104
  • 292
  • 461
  • Database triggers would be my preferred approach to this. Simpler than using Hibernate's interceptors. – skaffman Oct 17 '10 at 10:52
  • DB triggers are not so easy with my app. I need to record extra information in each audit entry, including the change that was reverted to, the change each change was based on, etc. and a cascading mechanism that handles this for collections. – at. Oct 17 '10 at 10:57
  • 1
    @skaffman: triggers move logic into the database layer. Using an ORM, between others, helps us keep the logic where it belongs, in the application layer. – cherouvim Oct 18 '10 at 06:39
  • @cherouvim: Well, that's one opinion. I'd argue that audit tables are about data integrity, not business logic, and that *does* belong in the database. – skaffman Oct 18 '10 at 07:08
  • I'd go with overwriting EmptyInterceptor. It is straight forward and easy to use. IMO the best thing about this is the AfterTransactionComplete-Method. Use other methods to collect changes and in AfterTxComplete check the Tx-State and on success persist your Audit-Logs before Interceptor-Reset. – zoidbeck Oct 18 '10 at 19:11

1 Answers1

2

I think the essential difference between the two is that you can only define one Interceptor in your SessionFactory, but you can register many listeners for a particular event.

I'm going to use Interceptors since I only want something very simple: a timestamp when my entity is created (the @Version annotation takes care of updating the lastModified property).

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
    <property name="packagesToScan" value="com.x.domain" />
    <property name="entityInterceptor" ref="onSaveInterceptor" />
</bean>

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/events.html#objectstate-interceptors

Eliseo Soto
  • 1,252
  • 2
  • 13
  • 18