users@glassfish.java.net

Re: How do I intercept database calls

From: <glassfish_at_javadesktop.org>
Date: Wed, 09 Sep 2009 00:08:19 PDT

So far I know, you can't. You can no explicitly listen to the underlying SQL statement generated by the EntityManager. But you can listen to the events at the EntityManager level, namely persist, remove, update and load. Beware that you won't get the callback if you use native queries, especially to to bulk update.

Have a look at this one, it could give some insight how to do it (I used EntityListener but not for this purpose): https://www.hibernate.org/195.html

Another way would be to use a trigger at the database level to track changes.

Small recap from javadoc:
@PrePersist Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.
@PreRemove Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
@PostPersist Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
@PostRemove Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
@PreUpdate Executed before the database UPDATE operation.
@PostUpdate Executed after the database UPDATE operation.
@PostLoad Eexecuted after an entity has been loaded into the current persistence context or an entity has been refreshed.
[Message sent by forum member 'ewernli' (erwann.wernli_at_gmail.com)]

http://forums.java.net/jive/thread.jspa?messageID=363321