We implemented an historian based on the Audit Logging example in Chapter 8.3.2 in Hibernate in action, which may be an alternative to the Event Listener strategy.
This is what I did:
1.Created an Historizable Interface which all objects that uses the history functionality should implement (Can use just an empty interface)
2.Create an MyInterceptor class, which implements the Interceptor class
Code:
public class MyInterceptor implements Interceptor {
private Set historySet = new HashSet();
public void postFlush(Iterator iterator) {
try {
Iterator historyElements = historySet.iterator();
while (historyElements.hasNext()) {
HistoryLog.logRecord(historyElements.next());
}
} finally {
historySet.clear();
}
}
public boolean onSave(Object object, Serializable serializable, Object[] obj2, String[] str, Type[] type) {
if (object instanceof Historizable) {
Historizable historizable = (Historizable) object;
historySet.add(historizable);
}
return false;
}
public boolean onFlushDirty(Object object, Serializable serializable, Object[] newValues, Object[] oldValues, String[] properties, Type[] type) {
if (object instanceof Historizable) {
Historizable historizable = (Historizable) object;
historySet.add(historizable);
}
return false;
}
public void onDelete(Object obj, Serializable serializable, Object[] obj2, String[] str, Type[] type) {
if (obj instanceof Auditable) {
Historizable historizable = (Historizable) object;
historySet.add(historizable);
}
}
}
(The other methods defined in the Interceptor interface uses default implementation)
3.Enabling the Interceptor by adding configuration line in the hibernate-service.xml file, by setting the SessionFactoryInterceptor attribute
Code:
<server>
<mbean code="org.jboss.hibernate.jmx.Hibernate" name="jboss.har:service=Hibernate">
<attribute name="DatasourceName">java:/MSSQLDS</attribute>
<attribute name="Dialect">org.hibernate.dialect.SQLServerDialect</attribute>
<attribute name="SessionFactoryName">java:/hibernate/SessionFactory</attribute>
<attribute name="CacheProviderClass">org.hibernate.cache.HashtableCacheProvider</attribute>
<attribute name="SessionFactoryInterceptor">com.saic.antares.dal.MyInterceptor</attribute>
<attribute name="ShowSqlEnabled">false</attribute>
</mbean>
</server>
Hope this can help you!