`
daichangfu
  • 浏览: 260325 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

hibernate EmptyInterceptor审计日志实现

阅读更多
@MappedSuperclass
public abstract class BaseAuditModel extends BaseCrmModel{
	/**
	 * UID
	 */
	private static final long serialVersionUID = 8886136517524378574L;

	public abstract String[][] getAuditPropertys(); //需要审计的字段名称
	
}

 

@Entity
@Table(name = "crm_user")
public class UserModel extends BaseAuditModel{

	/**
	 * UID
	 */
	private static final long serialVersionUID = 1L;
	
	private String userName; //用户名
	private String mobile;	//手机号
	private String address; //住址

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String[][] getAuditPropertys() {
		//需要审计的字段/解释
		return new String[][]{{"userName", "用户名"}, {"mobile","手机号"}, {"address", "住址"}};
	}

	@Override
	public String getModelName() {
		return "用户信息";
	}

}

 

public class LogEntityInterceptor extends EmptyInterceptor {
	/**
	 * UID
	 */
	private static final long serialVersionUID = 1L;
	
	private Logger log = Logger.getLogger(LogEntityInterceptor.class);
	
	@Override
	public void onDelete(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {

		log.info("删除数据 onDelete...");
		
	}
	
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		log.info("保存数据 onSave...");
		return false;
	}
	
	
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		log.info("修改数据 onFlushDirty..." + entity.getClass());
		if(entity instanceof BaseAuditModel){
			BaseAuditModel audit = (BaseAuditModel) entity;
			if(audit.getAuditPropertys() != null && previousState != null){
				log.info(audit.getModelName());
				log.info("id: "+audit.getId());
				Map<String, String> map = MapUtils.putAll(new HashMap(), audit.getAuditPropertys());
				for(int i=0, len=previousState.length; i<len; i++){
					if(previousState[i]!=null 
							&& map.get(propertyNames[i]) != null
							&& !previousState[i].equals(currentState[i])){
						log.info(propertyNames[i]+"/"+map.get(propertyNames[i])+":原值="+previousState[i]+",新值="+currentState[i]);
					}
				}
			}
		}
		return false;
	}
	
}

 

<!-- Hibernate审计日志拦截器 -->
<bean id="logEntityInterceptor" class="com.hzwealth.app.crm.LogEntityInterceptor" />

<bean id="sessionFactory"  ............. >
   ................
   <property name="entityInterceptor" ref="logEntityInterceptor"/>
   ................
</bean>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics