|
您可以在開啟Session時載入一個自訂Interceptor,這個Interceptor會在對應的動作發生之前呼叫對應的方法,方法是讓您定義的
Interceptor實作Interceptor介面,介面的定義如下: 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); } 假設您實作了SomeInterceptor類別: package
onlyfun.caterpillar;
.... public class SomeInterceptor implements Interceptor { .... } 在開啟Session時,可以如下載入自訂的Interceptor: SomeInterceptor
someInterceptor = new SomeInterceptor();
Session session = sessionFactory.openSession(someInterceptor); .... |