Hi, just wondering how to make the following interceptor thread-safe without sacrifice on performance in real application?
And when postFlush() being called, can I assume the transaction has been successfully submitted? And I guess when onFlushDirty() being called I can't start to write the audit log yet as the transaction may be rolled back. Am I right?
Thank you so much.
Code:
public class AuditLogInterceptor extends EmptyInterceptor {
private Session session;
private Long userId;
private Set inserts = new HashSet();
private Set updates = new HashSet();
public void setSession(Session session) {
this.session=session;
}
public void setUserId(Long userId) {
this.userId=userId;
}
public boolean onSave(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types)
throws CallbackException {
if (entity instanceof Auditable)
inserts.add(entity);
return false;
}
public boolean onFlushDirty(Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types)
throws CallbackException {
if (entity instanceof Auditable)
updates.add(entity);
return false;
}
public void postFlush(Iterator iterator)
throws CallbackException {
try {
for (Iterator it = inserts.iterator(); it.hasNext();) {
Auditable entity = (Auditable) it.next();
AuditLog.logEvent("create",entity,userId,session.connection());
}
for (Iterator it = updates.iterator(); it.hasNext();) {
Auditable entity = (Auditable) it.next();
AuditLog.logEvent("update",entity,userId,session.connection());
}
} finally {
inserts.clear();
updates.clear();
}
}
}