Hibernate 3 actually implements most of its functionality as event listeners. Event listeners are always registered globally for the event that they handle. You can register them in the configuration file or programmatic ally. Either way, you will need to map your implementation of one of the interfaces to the associated types.Here is the different types of events supported by hibernate
AutoFlushEventListener
DeleteEventListener
DirtyCheckEventListener
EvictEventListener
FlushEventListener
FlushEntityEventListener
LoadEventListener
InitializeCollectionEventListener
LockEventListener
MergeEventListener
PersistEventListener
PostDeleteEventListener
PostInsertEventListener
PostLoadEventListener
PostUpdateEventListener
PreDeleteEventListener
PreInsertEventListener
PreLoadEventListener
PreUpdateEventListener
RefreshEventListener
ReplicateEventListener
SaveOrUpdateEventListener
Let us consider the following example
public class EventExample {
public static void main(String[] args) {
Configuration config = new Configuration();
// Apply this event listener (programmatically)
config.setListener("save-update", new BookingSaveOrUpdateEventListener());
SessionFactory factory = config.configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Make our bookings... seat R1 is NOT to be saved.
session.saveOrUpdate(new Booking("charles","R1"));
session.saveOrUpdate(new Booking("camilla","R2"));
// The confirmation letters should not be sent
// out until AFTER the commit completes.
tx.commit();
}
}
import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.def.DefaultSaveOrUpdateEventListener;
public class BookingSaveOrUpdateEventListener
extends DefaultSaveOrUpdateEventListener
{
public Serializable onSaveOrUpdate(SaveOrUpdateEvent event)
throws HibernateException {
if( event.getObject() instanceof Booking) {
Booking booking = (Booking)event.getObject();
System.out.println("Preparing to book seat " + booking.getSeat());
if( booking.getSeat().equalsIgnoreCase("R1")) {
System.out.println("Royal box booked");
System.out.println("Conventional booking not recorded.");
// By returning null instead of invoking the
// default behavior‚ we prevent the invocation
// of saveOrUpdate on the Session from having
// any effect on the database!
return null;
}
}
// The default behavior:
return super.onSaveOrUpdate(event);
}
}
The objective of the listener is to prevent R1 from getting saved so the default behavior is overridden by the listener class.