2016-07-27 148 views
1

我想在我的spring + hibernate代碼中使用攔截器。休眠攔截器不起作用

的攔截器的定義是象下面這樣:

public class myInterceptor extends EmptyInterceptor{ 

private static final long serialVersionUID = 1L; 
Session session; 

public void setSession(Session session) { 
    this.session=session; 
} 

public boolean onSave(Object entity,Serializable id, 
    Object[] state,String[] propertyNames,Type[] types) 
    throws CallbackException { 
    System.out.println("onSave"); 
    return false; 
} 

public boolean onFlushDirty(Object entity,Serializable id, 
    Object[] currentState,Object[] previousState, 
    String[] propertyNames,Type[] types) 
    throws CallbackException { 
    System.out.println("onFlushDirty"); 
    return false; 
} 

public void onDelete(Object entity, Serializable id, 
    Object[] state, String[] propertyNames, 
    Type[] types) { 
    System.out.println("onDelete");  
} 

//called before commit into database 
public void preFlush(Iterator iterator) { 
    System.out.println("preFlush"); 
} 

//called after committed into database 
public void postFlush(Iterator iterator) { 
    System.out.println("postFlush");  
    }   
} 

和我的攔截器配置和使用的DAO類與Hibernate DAO支持擴展是

myInterceptor interceptor = new myInterceptor(); 
    SessionFactory sessionFactory = getSessionFactory(); 
    SessionBuilder sessionBuilder = sessionFactory.withOptions(); 
    Session session = sessionBuilder.interceptor(interceptor).openSession(); 
    interceptor.setSession(session); 

    Transaction tx = session.beginTransaction(); 

    session.merge(member); 
    tx.commit(); 
    session.close(); 

(我做的,而不是這個SessionFactory的配置太)

第一個問題是我的攔截器的功能不工作,除了preFlush和postFlush!

第二個問題是我如何使用這個攔截器作爲SessionFactory的一般配置,但只處理我的特定對象而不是所有對象。

+0

請分享EmptyInterceptor代碼 –

+0

@NarendraPandey它在org.hibernate包中,它不是我的代碼。 –

回答

1

您的攔截器方法onSave,onFlushDirty和onDelete不會在代碼中調用,因爲您不添加,修改或刪除實體。嘗試創建,修改和刪除管理實體,它將工作。

您不能爲特定實體配置攔截器;你將不得不編寫instanceofs或getClass()。isAssignableFrom()或類似的方法來限制你的行爲。

+0

我試圖實現Interceptor類而不是擴展空的攔截器,並最終它的工作! Tnx回答第二個問題。這是有幫助的。 –