I would like to inject on all session.save() like below.
public class MyHbnSession implements Session {
@Override
public Serializable save(Object obj) throws HibernateException {
if(obj instanceof MyClass) {
MyClass mc = (MyClass) obj;
mc.setVal("Injected Prop");
}
return super.save(obj);
}
}
And then whenever i getSession i should receive my custom session object
MyHbnSession session = HibernateUtil.getSessionFactory().openSession();
I could not find how to do this with hibernate. And two major things i miss
Kindly throw me some light on what i'm missing. Thanks for any help.
PS : I can do it with aspectj but don't want to due to many reasons.
With the help of @pdem answer hint and this post i was able to solve the problem. Here's the gist of what i did.
Interceptor Implementation
import java.io.Serializable;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
public class MyHbnInterceptor extends EmptyInterceptor {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
if(entity instanceof MyClass) {
// TODO: Do your operations here
}
return super.onSave(entity, id, state, propertyNames, types);
}
}
Letting know hibernate about our interceptor can be done in two ways
Session session = sf.openSession( new MyHbnInterceptor() );
new Configuration().setInterceptor( new MyHbnInterceptor() );
Know more in this link.
Cheers!