I think that I've found a solution, but it seems a little odd.
First, I reverted the onPreInsert so it looked like this:
Code:
public boolean onPreInsert(PreInsertEvent event)
{
if (AuditedEntityState.class.isAssignableFrom(event.getEntity().getClass()))
{
String[] names = event.getPersister().getPropertyNames();
for (int i = 0; i < names.length; ++i)
{
if ("creationTime".equals(names[i]))
{
Calendar time = Calendar.getInstance(utcZone);
event.getState()[i] = time;
if (log.isDebugEnabled())
{
log.debug("Setting creation time for entity of class " +
event.getEntity().getClass().getSimpleName() + " in state element " + i);
}
break;
}
}
}
return false;
}
Tracing through the log, it is clear that the reason this seemed to be ignoring the state change was because Hibernate is correctly writing the date on the insert, but is then doing an update with a null date!
So, I've now altered the code to be:
Code:
public boolean onPreInsert(PreInsertEvent event)
{
if (AuditedEntityState.class.isAssignableFrom(event.getEntity().getClass()))
{
String[] names = event.getPersister().getPropertyNames();
for (int i = 0; i < names.length; ++i)
{
if ("creationTime".equals(names[i]))
{
Calendar time = Calendar.getInstance(utcZone);
event.getState()[i] = time;
((AuditedEntityState)event.getEntity()).setCreationTime(time);
if (log.isDebugEnabled())
{
log.debug("Setting creation time for entity of class " +
event.getEntity().getClass().getSimpleName() + " in state element " + i);
}
break;
}
}
}
return false;
}
(ie set the calendar both in the state array
and the entity)
This works! The database holds the correct value, and only the insert occurred - no update.
I'm sure this can't be the intended way of working, but the main thing is that it works.
Thanks for all your help.
Regards
Brian