Is this the right way to do it?
Code:
public class GekkoEventListener implements PreInsertEventListener {
@Override
public boolean onPreInsert(PreInsertEvent event) {
handleSummaryAuditableEntity(
event.getEntity(), event.getPersister(), event.getState(), true);
return false;
}
private void handleSummaryAuditableEntity(
Object entity,
EntityPersister persister,
Object[] state,
boolean isPersist)
{
if (!(entity instanceof SummaryAuditable)) {
return;
}
if (log.isTraceEnabled()) {
log.trace("onPreInsert() called on SummaryAuditable: " + entity.getClass().getSimpleName());
}
User loggedInUser = // get currently logged in user
Date now = new Date();
if(isPersist){
setPropertyValue(persister, state, "dateCreated", now);
setPropertyValue(persister, state, "userCreated", loggedInUser);
}
setPropertyValue(persister, state, "dateUpdated", now);
setPropertyValue(persister, state, "userUpdated", loggedInUser);
}
private void setPropertyValue(
EntityPersister persister,
Object[] state,
String propName,
Object propValue)
{
int propIndex =
Arrays.asList(persister.getPropertyNames()).indexOf(propName);
state[propIndex] = propValue;
}
It seems to be working well enough for now (bootstrap data loading issues aside, see below).
Anyone got any experience with using the EventListener stuff this way? The book/manual only really talk about doing this stuff in the old interceptor way, I assume this is pretty much funcitonally identical?
Related to the structure given above (with the userCreated, userUpdated properties): is there any way I can get Hibernate to help me bootstrap the initial user into the system?
Our User object has a mandatory Title object (ie. non-null foreign key), and both of them are SummaryAuditable. So there's a circular dependency issue when inserting the "system" bootstrap user. We're using Hibernate to generate the schema, so we don't know the foreign key names, which means we can't (easily) just write a simple bootstrap load user script.
P.S. Hibernate 3.2