Can anyone help me to audit a table which has composite primary key ?
In my logchanges () method, I am persisting the EntityId to the AuditLog table, Incase if the table has a single Primary key, the Entity Id will be filled with proper values.
For me the requirement is to even log the composite PK values, but i am not able to log because, i don't know what are all the fields are Primary keys.
Please help me out. In the AbstractSaveEventListener, i am able to get the Identifiers for the object, but In the Interceptor's save method, i am not able to access either the SessionImplementor or Session, so i am not able to get the Identifier for the Objects. I need to implement this as the earliest. Please help me out in resolving this issue.
I am attaching the sample code of my OnSave() & logChanges() from my Interceptor.
Code:
public boolean onSave(Object obj, Serializable id, Object[] newValues, String[] properties, Type[] types)
throws CallbackException {
if (obj instanceof Auditable ) {
System.out.println("Inside instanceOf Auditable");
try {
Class objectClass = obj.getClass();
String className = objectClass.getName();
String[] tokens = className.split("\\.");
int lastToken = tokens.length - 1;
className = tokens[lastToken];
logChanges(obj, null, null, id.toString(), INSERT, className);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void logChanges(Object newObject, Object existingObject, Object parentObject,
String persistedObjectId, String event, String className)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Field[] fields = getAllFields(newObject.getClass(), null);
for(int i=0; i<fields.length; i++)
{
fields[i].setAccessible(true);
}
if(event.equals(INSERT)) {
AuditLogRecord logRecord = new AuditLogRecord();
logRecord.setEntityName(className);
logRecord.setMessage(event);
[b][color=blue][b] logRecord.setEntityId(persistedObjectId);[/b][/color][/b] logRecord.setCreatedBy(getUserInfo());
Method method = null;
try {
method = newObject.getClass().getMethod("toString",null);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = (String)method.invoke(newObject,null);
logRecord.setNewValue(str);
logRecord.setOldValue("");
logRecord.setCreatedDate(new Date());
if(parentObject == null) {
logRecord.setEntity( newObject);
} else {
logRecord.setEntity( parentObject);
}
inserts.add(logRecord);
}
}