Automatic time-stamping of persisted data
Posted by Martin Homik | Posted in Java, WebApp | Posted on 08-04-2008
2
In my scenario, I want to know when a persisted object has been modified. This information should be stored in the database. There are a few approaches to do that.
- In the database — I’ve read this suggestion somewhere that you can set a trigger. However, not all databases support this feature. Moreover, database independence is crucial. Setting a trigger as Java Annotation or property would be more convenient.
- AOP — Write a Spring aspect that intercepts calls to Hibernate/Database and add the current time-stamp to the appropriate field.
- JPA @Version — This was a promising approach. Unfortunately, edited objects were not updated but newly inserted. See a description here.
- JPA Listeners – by implementing JPA listeners and using @PrePersist annotations this would be the most convenient and elegant way to implement the requirement. For some reason, entity listeners don’t work with AppFuse/Hibernate. Speculations point to Hibernate not supporting this feature.
- Hibernate Interceptor – Similar to an aspect, one could implement a Hibernate Interceptor. However this approach bind the application to a specific Persistence Framework and prevents other persistency options in future. While this is a nice decision, one has to bear in mind that JPA is a small subset of features provided by each persistence framework. Hibernate is by far much more expressive than JPA and offers much more support than other frameworks. I fear that in the future, I will decide in favour of Hibernate as it offers much more support.
- Manual — probably the worst solution is to leave the developer in full control. That is, he has to care that a timestamp is added and modified whenever an object is edited. This approach error-prone as changing the modified time-stamp can be forgotten. Morever, there can be a delay between setting the modified time-stamp and the actual persist action to the database.
The only option left is to give Spring AOP a shot. Let’s go!


Did you end up implementing the spring AOP interceptor?
No, finally I solved it (maybe less elegant) in the Logic Layer by overwriting the save method. There I set the ‘modified’ field to the current date. Depending on whteher the POJO is a new entity I also set the created date timestamp. In the last step I call the save method of the super class.