Hibernate拦截器(Interceptor)【转】

来源:互联网 发布:软件需求文档ppt 编辑:程序博客网 时间:2024/05/19 03:17
   拦截器(Intercept):与Struts2的拦截器机制基本一样,都是一个操作穿过一层层拦截器,每穿过一个拦截器就会触发相应拦截器的事件做预处理或善后处理。

   Hibernate为我们提供了实现拦截器的接口org.hibernate.Interceptor,它里面提供了许多拦截事件。通常不需要实现这个接口,因为我们实现自己的拦截器不可能每一个事件都是必须的。所以Hibernate为我们提供了org.hibernate.Interceptor接口的一个空实现类org.hibernate.EmptyIntercept,通常情况下我们只需继承这个空实现类,Override需要的事件方法即可。
    拦截器的工作原理简易示意图:

设置拦截器后,相应的操作都会先穿过一层层相应的拦截器,让拦截器执行预处理或善后处理。

拦截器使用实例:
public class AutoUpdateTimeInterceptor extends EmptyInterceptor{    private static final long serialVersionUID = -8597658125309889388L;        /*     * entity - POJO对象     * id - POJO对象的主键     * state - POJO对象的每一个属性所组成的集合(除了ID)     * propertyNames - POJO对象的每一个属性名字组成的集合(除了ID)     * types - POJO对象的每一个属性类型所对应的Hibernate类型组成的集合(除了ID)     */    @Override    public boolean onSave(Object entity, Serializable id, Object[] state,            String[] propertyNames, Type[] types)    {            if (entity instanceof People)        {            for (int index=0;index<propertyNames.length;index++)            {                /*找到名为"checkinTime"的属性*/                if ("checkinTime".equals(propertyNames[index]))                {                    /*使用拦截器将People对象的"checkinTime"属性赋上值*/                    state[index] = new Timestamp(new Date().getTime());                    return true;                }            }        }        return false;    }} 
场景类
public class Client{    public static void main(String[] args)    {        /*为Session添加拦截器*/        Session session = HibernateUtil.getSessionFactory().openSession(new AutoUpdateTimeInterceptor());        Transaction tx = null;        try        {            tx = session.beginTransaction();                        People people = new People();            people.setName("zhangsan");                        session.save(people);                        tx.commit();        }        catch (Exception e)        {            if(tx!=null)            {                tx.rollback();            }                        e.printStackTrace();        }        finally        {            session.close();        }    }}

场景类中并没有显示的设置了people对象的"checkinTime"的属性值,启动该场景类代码,现在来查看数据库信息:

可以看到checkin_time这列属性依然被赋值了,说明该赋值操作是拦截器帮助我们完成的。使用拦截器的时候需要注意拦截器的返回值,我以前一直以为拦截器的返回值会控制一个操作是否可以继续,通过实验发现,即使返回false操作也会继续执行的,只是返回false的话,拦截器的所有设置都是无效的,不会反应到数据库中。
返回false:
public class AutoUpdateTimeInterceptor extends EmptyInterceptor{    private static final long serialVersionUID = -8597658125309889388L;        /*     * entity - POJO对象     * id - POJO对象的主键     * state - POJO对象的每一个属性所组成的集合(除了ID)     * propertyNames - POJO对象的每一个属性名字组成的集合(除了ID)     * types - POJO对象的每一个属性类型所对应的Hibernate类型组成的集合(除了ID)     */    @Override    public boolean onSave(Object entity, Serializable id, Object[] state,            String[] propertyNames, Type[] types)    {            if (entity instanceof People)        {            for (int index=0;index<propertyNames.length;index++)            {                /*找到名为"checkinTime"的属性*/                if ("checkinTime".equals(propertyNames[index]))                {                    /*使用拦截器将People对象的"checkinTime"属性赋上值*/                    state[index] = new Timestamp(new Date().getTime());//                  return true;                }            }        }        return false;    }}

查看插入的数据:

可以看到数据依然保存到数据库中了,但拦截器的操作并没有反映到数据库中,拦截器的操作是无效的。
但是比较奇怪的是Console输出的SQL语句:
Hibernate:     insert into people (name, checkin_time, id) values (?, ?, ?)Hibernate:     update  people set name=?, checkin_time=? where id=?
居然多了一条Update语句,我使用了p6spy显示了这两条SQL语句的绑定值:
1327304507491|0|0|statement|insert into people (name, checkin_time, id) values (?, ?, ?)|insert into people (name, checkin_time, id) values ('zhangsan', '2012-01-23 15:41:47.45', '402881e53509837f0135098380370001')1327304507491|0|0|statement|update people set name=?, checkin_time=? where id=?|update people set name='zhangsan', checkin_time='' where id='402881e53509837f0135098380370001'

可以看到,拦截器的操作会直接反映到数据库中的,但是如果返回值是false的话,Hibernate会产生一条Update SQL语句将拦截器的操作结果取消了。
最后,Hibernate的拦截器有两种设置方式,一种是使用sessionFactory.openSession(Interceptor interceptor),这样的拦截器只会针对该session有效,又叫做局部拦截器。另一种是使用Configuration的setInterceptor(Interceptor interceptor)方法设置,这样的拦截器对每一个session都有效,又称之为全局拦截器。





原创粉丝点击