您也可以使用攔截器來設置值
創建一個名爲時間戳的接口,你的實體imple換貨
public interface TimeStamped {
public Date getCreatedDate();
public void setCreatedDate(Date createdDate);
public Date getLastUpdated();
public void setLastUpdated(Date lastUpdatedDate);
}
定義攔截
public class TimeStampInterceptor extends EmptyInterceptor {
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState,
Object[] previousState, String[] propertyNames, Type[] types) {
if (entity instanceof TimeStamped) {
int indexOf = ArrayUtils.indexOf(propertyNames, "lastUpdated");
currentState[indexOf] = new Date();
return true;
}
return false;
}
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
if (entity instanceof TimeStamped) {
int indexOf = ArrayUtils.indexOf(propertyNames, "createdDate");
state[indexOf] = new Date();
return true;
}
return false;
}
}
並與會話工廠
使用時間戳列進行樂觀鎖定是個壞主意。始終使用整數版本列。原因在於,2個JVM可能處於不同的時間,並且可能不具有毫秒級的準確性。如果您改爲使用數據庫時間戳進行休眠,那將意味着來自數據庫的額外選擇。相反,只需使用版本號。 – sethu 2013-02-18 04:46:26