这几天发现Hibernate中的Interceptor 的作用.使我很受感动.现在把他介绍给大家,希望对大家有帮助.也好相互学习
你可以在开启Session时载入一个自定义的Interceptor这个Interceptor会在对应的操作发生之前调用对应的方法,方法是你定义的实现了Interceptor接口的类的方法.Interceptor接口定义如下:
java 代码
- package org.hibernate;
- import java.io.Serializable;
- import java.util.Iterator;
- import org.hibernate.type.Type;
- public interface Interceptor {
- // 载入对象前执行
- public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
- throws CallbackException;
- // flush 时,如果发现有Dirty data,则执行此方法
- public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException;
- // 保存对名象前执行
- public boolean onSave(Object entity, Serializable id, Object[] state, String[]propertyNames, Type[] types) throws CallbackException;
- // 刪除对象前执行
- public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;
- // 在 flush 前执行
- public void preFlush(Iterator entities) throws CallbackException;
- // 在 flush 后执行
- public void postFlush(Iterator entities) throws CallbackException;
- // 判断传入的对象是否为 transient 状态
- public Boolean isTransient(Object entity);
- // flush 前呼叫这个法判断 Dirty data
- // 传回Dirty data属性索引或null
- public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types);
- // 手动创建对象实体,如果传回 null,則使用预定的建造方法建立实例例
- public Object instantiate(String entityName, EntityMode entityMode, Serializable id)
- throws CallbackException;
- // 传回对象名称
- public String getEntityName(Object object) throws CallbackException;
- // 取得实例化对象
- public Object getEntity(String entityName, Serializable id) throws CallbackException;
- // beginTransaction() 之后执行
- public void afterTransactionBegin(Transaction tx);
- // 在事务完成前执行
- public void beforeTransactionCompletion(Transaction tx);
- // 在事务完成后执行
- public void afterTransactionCompletion(Transaction tx);
- }
咱们自定一个MyInterceptor类:
java 代码
- package com.super;
- ....
- public class MyInterceptor implements Interceptor {
- ....
- }
在启用Session时可以载入自订的Interceptor:
- MyInterceptor myInterceptor = new MyInterceptor();
- Session session = sessionFactory.openSession(myInterceptor);
- ....