使用拦截器时按如下步骤进行:
( 1 )定义实现Interceptor接口的拦截器类
( 2 )通过Session启用拦截器,或者通过Configuration启用全局拦截器
请看示例代码(仅仅打印出标志代码):
public class MyInterceptor extends EmptyInterceptor
... {
//更新的次数
private int updates;
//插入的次数
private int creates;
//当删除数据时,将调用onDelete方法
public void onDelect(Object entity, Serializable id, Object[]
state, String[] propertyNames, Type[] types)
...{
//do nothing
}
//同步Session和数据库中的数据
public boolean onFlushDirty(Object entity, Serializable id,
Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types)
...{
//每同步一次,修改的累加器加1
yuuuuuuuuuuuuuuuuuuuuuuuuyuh++;
for (int i=0; i < propertyNames.length; i++)
...{
if ("lastUpdateTimestamp".equals(propertyNames[i]))
...{
currentState[i] = new Date();
return true;
}
}
return false;
}
//加载持久化实例时调用该方法
public boolean onLoad(Object entity, Serializable id,
Object[] state, String[] propertyNames, Type[] types)
...{
System.out.println("===============================");
for (int i=0; i < propertyNames.length; i++)
...{
if ("name".equals(propertyNames[i]))
...{
System.out.println(state[i]);
state[i] = "aaa";
return true;
}
}
return false;
}
//保存持久化实例时,调用该方法
public boolean onSave(Object entity, Serializable id,
Object[] state, String[] propertyNames, Type[] types)
...{
creates++;
for (int i=0; i < propertyNames.length; i++)
...{
if ("createTimestamp".equals(propertyNames[i]))
...{
state[i] = new Date();
return true;
}
}
return false;
}
//提交刷新
public void postFlush(Iterator entities)
...{
System.out.println("创建的次数:" + creates + ",更新的次数:"
+ updates);
}
public void preFlush(Iterator entities)
...{
updates = 0;
creates = 0;
}
//事务提交之前触发该方法
public void beforeTransactionCompletion(Transaction tx)
...{
System.out.println("事务即将结束");
}
//事务提交之后触发该方法
public void afterTransactionCompletion(Transaction tx)
...{
System.out.println("事务已经结束");
}
}
下面是使用局部拦截器的示例代码:
public class HibernateUtil
... {
//静态类属性 SessionFactory
public static final SessioFactory sessionFactory;
//静态初始化块,完成静态属性的初始化
static
...{
try
...{
//采用默认的hibernate.cfg.xml来启动一个Cofiguration的实例
Configuration configuration = new Cofiguration().configure();
//由Cofiguration的实例来创建一个SessionFactory实例
sessionFactory = cofiguration.buildSessionFactory();
}
catch (Throwable ex)
...{
System.err.println("初始化sessionFactory失败." + ex);
throw new ExceptionInInitializerError(ex);
}
}
//ThreadLocal是隔离多个线程的数据共享,不存在多个线程之间共享资源
//因此不再需要对线程同步
public static Session currentSession() throws HibernateException
...{
Session s = (Session)session.get();
//如果该线程还没有Session,则创建一个新的Session
if (s == null)
...{
s = sessionFactory.openSession();
//将获得的Session变量存储在ThreadLocal变量Session里
session.set(s);
}
return s;
}
//加拦截器的打开Session方法
public static Session currentSession(Interceptor it) throws HibernateException
...{
Session s = (Session)session.get();
if (s == null)
...{
//以拦截器创建Session对象
s = sessionFactory.openSession(it);
//将获得的Session变量存储在ThreadLocal变量Session里
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException
...{
Session s = (Session)session.get();
if (s != null)
s.close();
//这个不错。。
session.set(null);
}
}
下面是主程序使用拦截器的代码:
private void testUser()
... {
//以拦截器开始Session
Sessin session = HibernateUtil.currentSession(new MyInterceptor());
//开始事务
Transaction tx = session.beginTransaction();
//执行下面代码时,可以看到系统回调onSave等方法
/**//*
User u = new User();
u.setName("PROLOVE");
u.setAge(20);
u.setNataionality("中国");
session.persist(u);
*/
//执行下面代码时,可以看到系统回调onLoad等方法
Object o = session.load(User.class, new Integer(1));
System.out.println(o);
User u = (User)o;
System.out.println(u.getName());
//提交事务时,可以看到系统回调事务相关方法
tx.commit();
HibernateUtil.closeSession();
}
( 1 )定义实现Interceptor接口的拦截器类
( 2 )通过Session启用拦截器,或者通过Configuration启用全局拦截器
请看示例代码(仅仅打印出标志代码):
public class MyInterceptor extends EmptyInterceptor
... {
//更新的次数
private int updates;
//插入的次数
private int creates;
//当删除数据时,将调用onDelete方法
public void onDelect(Object entity, Serializable id, Object[]
state, String[] propertyNames, Type[] types)
...{
//do nothing
}
//同步Session和数据库中的数据
public boolean onFlushDirty(Object entity, Serializable id,
Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types)
...{
//每同步一次,修改的累加器加1
yuuuuuuuuuuuuuuuuuuuuuuuuyuh++;
for (int i=0; i < propertyNames.length; i++)
...{
if ("lastUpdateTimestamp".equals(propertyNames[i]))
...{
currentState[i] = new Date();
return true;
}
}
return false;
}
//加载持久化实例时调用该方法
public boolean onLoad(Object entity, Serializable id,
Object[] state, String[] propertyNames, Type[] types)
...{
System.out.println("===============================");
for (int i=0; i < propertyNames.length; i++)
...{
if ("name".equals(propertyNames[i]))
...{
System.out.println(state[i]);
state[i] = "aaa";
return true;
}
}
return false;
}
//保存持久化实例时,调用该方法
public boolean onSave(Object entity, Serializable id,
Object[] state, String[] propertyNames, Type[] types)
...{
creates++;
for (int i=0; i < propertyNames.length; i++)
...{
if ("createTimestamp".equals(propertyNames[i]))
...{
state[i] = new Date();
return true;
}
}
return false;
}
//提交刷新
public void postFlush(Iterator entities)
...{
System.out.println("创建的次数:" + creates + ",更新的次数:"
+ updates);
}
public void preFlush(Iterator entities)
...{
updates = 0;
creates = 0;
}
//事务提交之前触发该方法
public void beforeTransactionCompletion(Transaction tx)
...{
System.out.println("事务即将结束");
}
//事务提交之后触发该方法
public void afterTransactionCompletion(Transaction tx)
...{
System.out.println("事务已经结束");
}
}
下面是使用局部拦截器的示例代码:
public class HibernateUtil
... {
//静态类属性 SessionFactory
public static final SessioFactory sessionFactory;
//静态初始化块,完成静态属性的初始化
static
...{
try
...{
//采用默认的hibernate.cfg.xml来启动一个Cofiguration的实例
Configuration configuration = new Cofiguration().configure();
//由Cofiguration的实例来创建一个SessionFactory实例
sessionFactory = cofiguration.buildSessionFactory();
}
catch (Throwable ex)
...{
System.err.println("初始化sessionFactory失败." + ex);
throw new ExceptionInInitializerError(ex);
}
}
//ThreadLocal是隔离多个线程的数据共享,不存在多个线程之间共享资源
//因此不再需要对线程同步
public static Session currentSession() throws HibernateException
...{
Session s = (Session)session.get();
//如果该线程还没有Session,则创建一个新的Session
if (s == null)
...{
s = sessionFactory.openSession();
//将获得的Session变量存储在ThreadLocal变量Session里
session.set(s);
}
return s;
}
//加拦截器的打开Session方法
public static Session currentSession(Interceptor it) throws HibernateException
...{
Session s = (Session)session.get();
if (s == null)
...{
//以拦截器创建Session对象
s = sessionFactory.openSession(it);
//将获得的Session变量存储在ThreadLocal变量Session里
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException
...{
Session s = (Session)session.get();
if (s != null)
s.close();
//这个不错。。
session.set(null);
}
}
下面是主程序使用拦截器的代码:
private void testUser()
... {
//以拦截器开始Session
Sessin session = HibernateUtil.currentSession(new MyInterceptor());
//开始事务
Transaction tx = session.beginTransaction();
//执行下面代码时,可以看到系统回调onSave等方法
/**//*
User u = new User();
u.setName("PROLOVE");
u.setAge(20);
u.setNataionality("中国");
session.persist(u);
*/
//执行下面代码时,可以看到系统回调onLoad等方法
Object o = session.load(User.class, new Integer(1));
System.out.println(o);
User u = (User)o;
System.out.println(u.getName());
//提交事务时,可以看到系统回调事务相关方法
tx.commit();
HibernateUtil.closeSession();
}