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.

Comments

  1. Sameer

    I have both onSave and onFlushDirty implemented in my “UpdateInterceptor”

    Main purpose of this Interceptor is to update inserted/updated columns in each table, that go though an update/insert

    However, there are following statements generated in hibernate logs, where inserted/updated columns are not getting updated i.e.

    update CriteriaParameterValue set criteria_instance_id=?, sorting_order=? where id=?

    pasting my mapping file here…

    ================STARTs===========

    HdmCriteriaService_Seq


    <!– –>

    HdmCritTmpltGrp_seq

    hdm_srchtmpltgrp_seq

    criteria_parameter_value_seq

    criteria_instance_seq

    =================ENDs===========

Leave a comment

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

*