Question

I am using Hibernate Interceptor with (hibernate 4.x). I want to perform some operation on save method of Session. So I extend EmptyInterceptor.

It has following methods:

onSave() //when save operation is preformed.
postFlush() //called after committed into database 

PROBLEM: in postFlush() I want to perform SAVE operation. So my control stuck in loop. because whenver session.save() is being called my calls, onSave() and postFlush () method of EmptyInterceptor got called to intercept SAVE operation.

TO remove this problem I used TWO session factories. 1 for performing Session operations(save,update etc) and 2nd for HibernateIntercepter.

But I am worried how I can workout this problem with single sessionFactory??

public class AudiLogInterceptor extends EmptyInterceptor {

public boolean onSave(Object entity, Serializable id, Object[] state,
        String[] propertyNames, Type[] types) {
    return false;
}

// called after committed into database
public void postFlush(Iterator iterator) {
    // want to perform SAVE operation here with Session.save()
    // But whenever I open new seesion here. It falls in loop
    Session tempSession = HibernateUtil.hibernateTemplateLog
            .getSessionFactory().openSession();

    try {
        Item item = new Item();
        item.setName("anyItem");
        item.setValue("anyValue");
        tempSession.save(item);
        tempSession.flush();
    } finally {
        tempSession.close();
    }
    }
} 
Was it helpful?

Solution

You do not use interceptors to save the objects. You use it to modify/format the items and let the session object do the rest for your but not add new items.

If you really want to add a row at the end of the flush() or commit() then you use Spring-AOP to do that as one option. There you can add Advises to the hibernate services, so, you can save something immediately after running a method.

Work around I'd thought is the following.

public void postFlush(Iterator iterator) {


for(; iterator.hasNext();) {
   if(!(iterator.next() instanceof Item)){ //<<<<< You verify if you are saving Item or //other objects, if saving Item, skip this block.

   Session tempSession = HibernateUtil.hibernateTemplateLog
            .getSessionFactory().openSession();

    try {
        Item item = new Item();
        item.setName("anyItem");
        item.setValue("anyValue");
        tempSession.save(item);
        tempSession.flush();
    } finally {
        tempSession.close();
    }
}
}
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top