I have a custom EmptyInterceptor that I use to set information on the creation date, last modification date, created by user, and last modified user by overriding onSave
and onFlushDirty
.
This system has worked pretty well for us but we just found an issue where we have code that is blindly calling the setters on an entity using some input data. In this case, even if the data has not changed, hibernate will fire our custom interceptor and we'll set the last modified user and date. This causes Hibernate to update the entity in the database. We know this because we have an insert and update trigger on this table. If we disable the interceptor, Hibernate will not update the entity in the database.
We'd like to avoid setting the user and date if the entity hasn't really changed so no update happens in those situations. I've read about the way Hibernate does its dirty entity checking and I have the previousState
and currentState
arrays passed into onFlushDirty
and I can loop through to do this check myself. Is there any easier way to do that?
I looked at HibernateSession.isDirty() but that doesn't tell me if this particular entity has changed, just if there's a changed entity in the session.
UPDATE
It turns out that the offending code blindly calling setters was not the issue. It was the offending code setting a Collection of child objects instead of modifying the Collection that was already there. In this case, Hibernate thinks the entity has changed - or at least thinks so enough to call the Interceptor.