您也可以使用拦截器来设置值
创建一个名为时间戳的接口,你的实体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