Hi,
I'm using hibernate3 and implementing the PreUpdateEventListener to get notified when updates occur. The next aim is to insert a record of the update into Audit tables. For this need to know the table name that the updated entity is mapped to. How do I retrieve the table name.
Synopsis of my code public final class HibernateAuditLogListener implements PreDeleteEventListener, PreInsertEventListener, PreUpdateEventListener, Initializable { .... .... public final boolean onPreUpdate(PreUpdateEvent event) { if (event.getPersister() instanceof IAuditable) { try { final Long actorId = 0L; final Serializable entityId = event.getPersister().hasIdentifierProperty() ? event.getPersister().getIdentifier(event.getEntity(), event.getPersister().guessEntityMode(event.getEntity())) : null; final String entityName = event.getEntity().getClass().toString(); final Date transTime = new Date(); // new Date(event.getSource().getTimestamp()); final EntityMode entityMode = event.getPersister().guessEntityMode(event.getEntity()); Object oldPropValue = null; Object newPropValue = null;
// need to have a separate session for audit save StatelessSession session = event.getPersister().getFactory().openStatelessSession(); session.beginTransaction();
// get the existing entity from session so that we can extract existing property values Object existingEntity = session.get(event.getEntity().getClass(), entityId); String tableName = ??????????????? IAuditable auditableEntity = (IAuditable) event.getPersister();
// cycle through property names, extract corresponding property values and insert new entry in audit trail for (String propertyName : event.getPersister().getPropertyNames()) { newPropValue = event.getPersister().getPropertyValue(event.getEntity(), propertyName, entityMode); // because we are performing an insert we only need to be concerned will non-null values if (newPropValue != null) { // collections will fire their own events if (!(newPropValue instanceof Collection)) { oldPropValue = event.getPersister().getPropertyValue(existingEntity, propertyName, entityMode); if (!oldPropValue.equals(newPropValue)) { if (LOG.isDebug()) { LOG.debug("{" + OPERATION_TYPE_UPDATE + "} for: {" + entityName + "}, ID: {" + entityId + "}, property: {" + propertyName + "}, old value: {" + oldPropValue + "}, new value: {" + newPropValue + "}, actor: {" + actorId + "}, date: {" + transTime + "}"); } } } } }
session.getTransaction().commit(); session.close(); } catch (HibernateException e) { LOG.error("Unable to process audit log for UPDATE operation:" + e.getMessage()); } return false; } return false; }
|