Hibernate interceptors: Update entity’s properties “on update” and “on save”

An Hibernate interceptors provides a highly flexible way to hook into the session’s life-cycle to invoke your custom methods at particular session states, like before an entity is persisted and/or updated. Specially in multi-tier applications interceptors can be useful to plug in (entity) functionalities on a very clear way instead of scattering them through the hole application.

Here is a simple example for an interceptor that updates the property “created” when the entity (instance of MyObject in this example) is persisted (onSave) and “lastUpdate” when updated (onFlushDirty):

public class SampleInterceptor extends EmptyInterceptor {
  @Override
  public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
    if (!(entity instanceof MyObject)) return false;
    for (int i = 0; i < propertyNames.length; i++) {
      if ("created".equals(propertyNames[i])) state[i] = new Date();
    }
    return true;
  }
  @Override
  public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
    if (!(entity instanceof MyObject)) return false;
    for (int i = 0; i < propertyNames.length; i++) {
      if ("lastUpdate".equals(propertyNames[i])) currentState[i] = new Date();
    }
    return true;
  }
}

It is reasonable to use the EmptyInterceptor as base class for custom interceptors instead of implementing the Interceptor interface, because the EmptyInterceptor handles all life-cycle events your are not interested in with an empty/default implementation. Also, it is important to know, that changes that are made by invoking the entity’s setter method will not be persisted to the database. You have to change the entity’s state by modifying the passed state arrays. Unfortunately, this is a bit cumbersome and error-prone, especially if the name of the entity’s attribute will change.

Leave a comment

Your email address will not be published. Required fields are marked *

*