Hi, just wondering how to make the following interceptor thread-safe. Any idea or suggestions?
The interceptor is global scoped, not session-scoped.
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();
}
}
}