Hibernate 拦截器

Hibernate 为我们提供了实现拦截器的接口org.hibernate.Interceptor,它里面提供了许多拦截事件。通常不需要实现这个接口,因为我们实现自己的拦截器不可能每一个事件都是必须的。所以Hibernate为我们提供了org.hibernate.Interceptor接口的一个空实现类 org.hibernate.EmptyIntercept,通常情况下我们只需继承这个空实现类,Override需要的事件方法即可。
与Struts2的拦截器机制基本一样,都是一个操作穿过一层层拦截器,每穿过一个拦截器就会触发相应拦截器的事件做预处理或善后处理。
这里写图片描述

以下是在 Interceptor 接口中可用的所有方法的列表。
这里写图片描述

Hibernate的拦截器有两种设置方式

一种是使用sessionFactory.openSession(Interceptor interceptor),这样的拦截器只会针对该session有效,又叫做局部拦截器。另一种是使用Configuration的setInterceptor(Interceptor interceptor)方法设置,这样的拦截器对每一个session都有效,又称之为全局拦截器。

应用实例

创建拦截器:

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;  
    }  
} 

查看数据库中插入的数据,checkin_time的值为空,但是数据依然会保存到数据库中,只是拦截器的操作时无效的。
但是比较奇怪的是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语句将拦截器的操作结果取消了。
参考:http://developer.51cto.com/art/201202/314989.html
https://www.w3cschool.cn/hibernate/npyd1iek.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值