问题
I am trying to create an Audit table that will ends looking something like that :
entity,id,property,oldValue,newValue,user,timestamp
using hibernate EmptyInterceptor I expect that this table will have a lot of IO's . It seems that previouseState at onFlushDirty method is not working as I expected .
how can I get the old value without fetching it from the db as shown here ?
I was trying to follow this post
public class AuditLogInterceptor extends EmptyInterceptor {
private Set inserts = new HashSet();
private Set updates = new HashSet();
private Set deletes = new HashSet();
private Map oldies = new HashMap();
@Override
public boolean onSave(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types)
throws CallbackException {
if (entity instanceof Auditable)
inserts.add((Auditable)entity);
return false;
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
if (entity instanceof Auditable)
deletes.add((Auditable)entity);
}
@Override
public boolean onFlushDirty(Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types)
throws CallbackException {
if (entity instanceof Auditable) {
try {
// Use the id and class to get the pre-update state from the database
Session tempSession =
HibernateUtil.getSessionFactory().openSession();
Auditable old = (Auditable) tempSession.get(entity.getClass(), ((Auditable) entity).getId());
oldies.put(old.getId(), old);
updates.add((Auditable)entity);
} catch (Throwable e) {
_log.error(e,e);
}
}
return false;
}
is there a way of getting the get the pre-update state without a round trip to the db ?
回答1:
An alternative approach is to store the previous state on load.
@Entity
@Table(name='Foo')
class Foo {
@Transient
private Foo previousState;
@PostLoad
private void setPreviousState(){
previousState = new Foo();
//copy the fields
}
public Foo getPreviousState(){
return previousState;
}
}
来源:https://stackoverflow.com/questions/27529208/how-to-get-previousestate-without-fetching-from-the-db-using-hibernate-intercept