I do this by creating a Clone of the entity when it is loaded into the Bean and then comparing the Clone to the instance when I do an update.
I had to write the Clone and Compare methods in full (ie. field by field) as I couldn't find an easy method of creating a non-linked clone (so the Clone won't update when the instance updates)
Can I bother you in posting some code or more detailed info? :)
you could do this by defining a second entityManager and use this one to load the entity from the Database.
I would post my code but I think Alexander's method has just made mine redundant. I'd try that if I were you. In fact I think I'll be trying it myself.
It would go something like this:
<persistence:managed-persistence-context name="entityManager" auto-create="true" persistence-unit-jndi-name="java:/MyEntityManagerFactory"/> <persistence:managed-persistence-context name="secondaryEntityManager" auto-create="true" persistence-unit-jndi-name="java:/MyEntityManagerFactory"/>
Set your flush mode to manual. And then in your UserHome update() method:
User cloneUser = secondaryEntityManager.find(User.class, getId()); //now do a compare - this you will have to write manually String differences = UserCompare.compare(getInstance(), cloneUser);
Thank you guys. Got it working.
Beer's on me :)
just a (newbie) question on this (hope it's just my paranoia):
what about concurrent changes to your object?
- user A opens the page - data is read from em1 and displayed
- while user A is still working on the object, user B also opens the same object, edits it and saves it: now it has changed in the database
- user A is now ready and calls your update method, which uses em2 to find the object
but this object now is not what you expect!
it already includes the changes of user b when you do the comparision. but as I understood: you expect the object to be what user A saw when she opened the page
note: in this case user A will get an optimistic locking exception by hibernate so she can't update the object anyway.