• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JPA Detect changes in Entities automatically

 
Markus Schmider
Ranch Hand
Posts: 132
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Markus Schmider
Ranch Hand
Posts: 132
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for you reply.

I have tried something like that:







 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:




 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic