aspose file tools*
The moose likes Object Relational Mapping and the fly likes JPA Detect changes in Entities automatically Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "JPA Detect changes in Entities automatically" Watch "JPA Detect changes in Entities automatically" New topic
Author

JPA Detect changes in Entities automatically

Markus Schmider
Ranch Hand

Joined: Feb 25, 2007
Posts: 105
Is there a automatic way to detect if an object has changed since it has been fetched from the database.
I want to persist a whole object tree. But I must detect which objects of the tree have changes and then set the date and user on them.
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

You can use callback methods in your entities, or better yet an entity listener, to fill in audit information at various life cycle stages. In this case you could use listener with a @PreUpdate annotated method. Something like:




This is just a very minimal example to convey the basic idea. You could add much more audit data to the Auditable interface, and it would be a good idea to move the audit data fields out of the entity and into a seperate base class annotated as @MappedSuperclass. That sort of stuff.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Markus Schmider
Ranch Hand

Joined: Feb 25, 2007
Posts: 105
Thanks for you reply.

I have tried something like that:







Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

That's strange, but it may have to do with the way you've mapped the association between Order and Item, though and who "owns" the association.
I would probably map it something like this:




 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JPA Detect changes in Entities automatically