Hibernate 3.2, MySQL 5.0
Some of my data objects have create/update dates that get automagically populated by an interceptor. I can see the persistent entity getting this information set, but it is still being persisted as null.
Code snippets:
Code:
<hibernate-mapping>
<class name="UserData" table="user">
<meta attribute="implements">Auditable</meta>
<property name="createDate" column="usr_create_date" type="timestamp"/>
<property name="updateDate" column="usr_update_date" type="timestamp"/>
<property name="createBy" column="usr_create_by" type="string"/>
<property name="updateBy" column="usr_update_by" type="string"/>
</class>
</hibernate-mapping>
public interface Auditable extends Persistable {
Date getCreateDate();
Date getUpdateDate();
String getCreateBy();
String getUpdateBy();
void setCreateDate( Date createDate );
void setUpdateDate( Date updateDate );
void setCreateBy( String createBy );
void setUpdateBy( String updateBy );
}
class AuditInterceptor extends EmptyInterceptor {
protected void audit( Object entity, Object[] state ) {
if( entity instanceof Auditable ) {
Auditable data = (Auditable) entity;
//New audit info, create from scratch
Date now = new Date();
if( data.getCreateDate() == null ) {
data.setCreateDate( now );
data.setCreateBy( "this guy" );
}
data.setUpdateDate( now );
data.setUpdateBy( "this guy" );
}
}
public boolean onFlushDirty( Object entity, Serializable id, Object[] currentState,
Object[] previousState, String[] propertyNames, Type[] types )
throws CallbackException {
audit( entity, currentState );
return super.onFlushDirty( entity, id, currentState, previousState, propertyNames, types );
}
public boolean onSave( Object entity, Serializable id, Object[] state, String[] propertyNames,
Type[] types ) throws CallbackException {
audit( entity, state );
return super.onSave( entity, id, state, propertyNames, types );
}
}
//Some other class
Object executeFullTransaction( Object data ) throws Exception {
Object o = null;
Transaction transaction = null;
Session session = null;
try {
session = factory.openSession( new AuditInterceptor() );
transaction = session.beginTransaction();
session.saveOrUpdate( data )
session.flush();
transaction.commit();
} catch( Exception e ) {
if( transaction != null ) {
try {
transaction.rollback();
} catch( HibernateException rollbackerror ) {
log.warn( rollbackerror, rollbackerror ); //Can't do nothin'...
}
}
throw e;
} finally {
try {
session.close();
} catch( HibernateException e ) {
log.warn( e, e );
}
}
return o;
}
Now, in the debugger, I can see that audit() is definately firing and that the changes are happening in the entity object. But during actual persistence, the dates and bys are null. These code snippets are pasted and modified...ignore syntactical mistakes.
My data objects are auto-generated...Any reason why the persistent object could get a date parameter set and still have it persist as null? I'm boggled.