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