---
title: "Hibernate拦截器"
author: "wangyanlong0107"
date: "2012-07-04T15:40:39Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2012-07-04T15:40:39Z"
id: 1576559
url: "https://bigdragon.iteye.com/blog/1576559"
---

项目中每个表里都有相同的四个字段，创建时间，创建人，更新时间，更新人，这时我们可以通过拦截器在保存，更新之前设置他们的值

实现方法：   
首先写一个类继承org.hibernate.EmptyInterceptor或者实现org.hibernate.Interceptor接口：   
为了简单起见，一般直接继承org.hibernate.EmptyInterceptor就可以了。   
然后重载一下onFlushDirty方法和onSave方法就可以了。 

因为Hibernate会在更新数据时回调onFlushDirty方法，在插入数据时回调onSave方法。 

public class HibernateInterceptor extends EmptyInterceptor { //只要继承这个类就OK了

@Override  
public boolean onSave(Object entity, Serializable id, Object\[] state,  
    String\[] propertyNames, Type\[] types) {//这个保存到数据库之前，会执行的代码,entity是要保存的实体类  
   try {  
    PropertyUtils.setProperty(entity, "createTime", new Date());  
    if (ServletActionContext.getRequest() != null) {  
     PropertyUtils.setProperty(entity, "createUserID",  
       ServletActionContext.getRequest().getSession()  
         .getAttribute(Constants.LOGIN\_USER\_ID));  
    }  
   } catch (IllegalAccessException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
   } catch (InvocationTargetException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
   } catch (NoSuchMethodException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
   }  
   return super.onSave(entity, id, state, propertyNames, types);  
}

@Override  
public boolean onFlushDirty(Object entity, Serializable id,  
    Object\[] currentState, Object\[] previousState,//这个更新到数据库之前，会执行的代码,entity是要更新的实体  
    String\[] propertyNames, Type\[] types) {  
   try {  
    PropertyUtils.setProperty(entity, "updateTime", new Date());  
    if (ServletActionContext.getRequest() != null) {  
     PropertyUtils.setProperty(entity, "updateUserID",  
       ServletActionContext.getRequest().getSession()  
         .getAttribute(Constants.LOGIN\_USER\_ID));  
    }  
   } catch (IllegalAccessException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
   } catch (InvocationTargetException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
   } catch (NoSuchMethodException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
   }  
   return super.onFlushDirty(entity, id, currentState, previousState,  
     propertyNames, types);  
}

 

怎么让它起作用呢，在spring里配置文件加上下面的

&lt;bean id="hibernateInterceptor"  
   class="com.jsict.framework.interceptor.HibernateInterceptor" /&gt;   
    
&lt;bean id="sessionFactory"  
   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;  
   &lt;property name="dataSource"&gt;  
    &lt;ref bean="dataSource" /&gt;  
   &lt;/property&gt;  
   &lt;property name="entityInterceptor"&gt; //在sessionFactory里配置上这个就可以了，拦截器就起作用了  
    &lt;ref local="hibernateInterceptor" /&gt;  
   &lt;/property&gt;