Hibernate Interceptor

Object passes through different stages of its life and interceptor interface provides callback methods which can be used/called at different stages to perform required tasks.

It allows the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded.

You can either implement Interceptor directly or extend EmptyInterceptor.

There are two kinds of inteceptors: Session-scoped and SessionFactory-scoped.

A Session-scoped interceptor is specified when a session is opened.

e.g

Session session = sessfactory.withOptions( new MyInterceptor()).openSession();

A SessionFactory-scoped interceptor is registered with the Configuration object prior to session factory.

e.g

Configuration cfg = new Configuration().setInterceptor( new MyInterceptor());

Example:

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;

public class MyInterceptor extends EmptyInterceptor {
   private int updates;
   private int creates;
   private int loads;

   public void onDelete(Object entity,
                     Serializable id,
                     Object[] state,
                     String[] propertyNames,
                     Type[] types) {
       // It is called before an object is deleted.
   }

   // This method is called when Employee object gets updated.
   public boolean onFlushDirty(Object entity,
                     Serializable id,
                     Object[] currentState,
                     Object[] previousState,
                     String[] propertyNames,
                     Type[] types) {
	// It is called when dirty object is detected during a flush.
       if ( entity instanceof Employee ) {
          // do something
          return true; 
       }
       return false;
   }
   public boolean onLoad(Object entity,
                    Serializable id,
                    Object[] state,
                    String[] propertyNames,
                    Type[] types) {
       // It is called when an object is initialized.
       return true;
   }

   public boolean onSave(Object entity,
                    Serializable id,
                    Object[] state,
                    String[] propertyNames,
                    Type[] types) {
	//It is called when an object is saved.
       if ( entity instanceof Employee ) {
	// do something
          return true; 
       }
       return false;
   }

   public void preFlush(Iterator itr) {
	//It is called before a flush or object committed to database.
   }

   public void postFlush(Iterator itr) {
	//It is called after flush and object committed to database.
   }
}