I’m using Hibernate with Xml mappings. I have an entity that has two fields creationDate and updateDate of type timestamp, that have to be filled with the current UTC time when the entity is persisted and updated.
I know about the existence of the @PrePersist and @PreUpdate annotations, but i don’t know how to use their equivalent in my Xml mappings.
Again, i was wondering if Hibernate somehow supports natively the update and creation time set.
Thanks
The Hibernate3 event architecture provides something equivalent and you could register listeners for
PreInsertEvent,PreUpdateEventorSaveOrUpdateEvent(see theorg.hibernate.eventpackage for a full list) to set and update the create/update dates.Another approach would be to use an interceptor, either
Session-scoped orSessionFactory-scoped and to set bothcreateDateandupdateDateinonSave(...), update theupdateDateinonFlushDirty(...).Update: I’m leaving my original suggestions below but I think that the right approach (should have been my initial answer) is to use an interceptor or the event architecture.
You could use thegeneratedattribute of thetimestampto getcreationDateandupdateDategenerated by the database on insert and on insert and update respectively:Refer to the section on generated properties for full details.
Option 1
It appears that
timestampdoesn’t supportgenerateadso my suggestion won’t work. Nevertheless, having read the documentation more carefully, my understanding is thattimestampis an alternative to versioning and I don’t think that it’s an appropriate choice for fields likecreateDateandupdateDate(it may work for the later but that’s not whattimestampis for).So I would actually still use generated properties but with simple properties instead of
timestamp:At the database level, this would require using a trigger for
updateDatecolumn. For thecreateDatecolumn, using something likecurrent_timestampas default value would work nicely. But triggers are maybe not wanted…Option 2
To avoid the trigger of the Option 1, a variation would be to use
updateDatefor versioning (and thus map it astimestamp):Same approach as Option 1 for
createDate, use a default value at the database level.Option 3
See the top of this answer…