Hadi Ranjbar
Hadi Ranjbar

Reputation: 1802

Hibernate interceptor does not work

I am trying to use interceptors in my spring+hibernate code.

The inceptor definition is like below:

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

and my interceptor configuration and usage in dao class with hibernate dao support extend is

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

(I do SessionFactory configuration instead of this too)

1st problem is my interceptor's functions don't work except preFlush and postFlush!

2nd problem is how I can use this interceptor as SessionFactory general configuration, but only working on my specific object and not all objects.

Upvotes: 1

Views: 2439

Answers (1)

Uwe Allner
Uwe Allner

Reputation: 3467

Your interceptor methods onSave, onFlushDirty and onDelete are not called in your code, as you don't add, modify or delete entities. Try to create, modify and delete managed entities, and it will work.

You cannot configure the interceptor for specific entities; you will have to code instanceofs or getClass().isAssignableFrom() or like in your respective methods to restrict behaviour to those.

Upvotes: 1

Related Questions