一般我们创建实体对象,属性基本都会有一个创建时间createDate和一个修改时间modifyDate,这两个属性在实际应用中也有着很重要的作用,通常,我们在保存实体的时候,需要对这两个属性都赋值,而且都是new Date()的方式赋值,实体多了,这种赋值就显得不是那么的方便了,我们可以考虑使用hibernate拦截器来帮助我们给他们赋值,当我们创建实体的时候,我们对createDate和modifyDate都要赋值,当我们修改实体的时候,我们就只对modifyDate进行赋值。
我们实现这个interceptor需要继承EmptyInterceptor,然后覆盖onSave(),onFlushDirty()两个方法。如下所示:
package com.xxx.spring.hibernate.config;
import java.io.Serializable;
import java.util.Date;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
@SuppressWarnings("serial")
public class MyEntityInterceptor extends EmptyInterceptor{
private static final String CREATEDATE="createDate";
private static final String MODIFYDATE="modifyDate";
@Override
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {