persistence@glassfish.java.net

Re: Determine whether entity was changed

From: Mitesh Meswani <Mitesh.Meswani_at_Sun.COM>
Date: Fri, 10 Oct 2008 12:02:57 -0700

I think you can achieve this using standard JPA. Look at preUpdate
LifeCycle callback (section 3.5 from spec)

msmolyak wrote:
> Hello,
>
> I am writing a Spring MVC/EJB 3 application using JPA with TopLink
> Essentials. The application is deployed on Oracle AS 10.3.
>
> The entities in the application have persistent audit fields to keep track
> of who changed the entity and when. The audit fields are populated using EJB
> 3 interceptor mechanism. Each time a create or update is called on the
> Session Facade for an entity, the interceptor populates the audit fields,
> after which the entity is persisted.
>
> The problem with this approach is that the audit fields are updated
> regardless of whether the entity was actually updated or not. As long as
> update() was invoked (even if no field has changed its value) the audit
> fields will be updated and the TopLink will be forced to update the
> corresponding database table.
>
> I know that TopLink uses UnitOfWork mechanism to maintain the list of
> entities updated for the given transaction. Through it, TopLink knows which
> entities require writing to the database. My question is whether it is
> possible for my code in the audit field updating logic to determine whether
> the entity being processed has been changed. I understand that I can track
> the changes myself using a dirty flag, but I am trying to avoid it.
>
> How can I access the TopLink API and determine for the given entity (for
> which update() was called) whether it needs updating in the database?
>
> Thank you,
>
> Michael
>