[英]how to get previouseState without fetching from the db using hibernate interceptor to create audit trail table?
我正在嘗試創建一個審計表,它將最終看起來像這樣:
實體,id,屬性,舊值,新值,用戶,時間戳
使用休眠的EmptyInterceptor,我希望這個表會有很多IO。 似乎onFlushDirty方法中的previouseState無法正常工作。
我怎么能不得到如圖所示從數據庫中獲取它的舊值在這里 ?
我正在嘗試關注此帖子
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;
}
有沒有一種方法可以獲取獲取更新前的狀態而無需往返數據庫?
另一種方法是在加載時存儲先前的狀態。
@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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.