posted 10 years ago
What is the usual way to edit managed entities in a GUI (Swing, in my case) application?
My scenario: I have a list of entities (say, JList). It's populated by actual managed entities. User can select one entity and edit it, in which case the selected entity gets passed to an edit form. The edit form can modify the entity (say, add or remove something from collections in the entity) and always displays the current contents of the entity. My problem is how to handle the situation when user cancels the edit form - I need to "undo" the changes made to the entity in the form.
I can think of several approaches:
1) When the uses cancels the edits (or he saves, but the persist operation fails), I'll revert the entity, probably by reloading its state from the database. My problem is that I don't know whether this is at all possible. I also don't like the reloading bit, but I'd swallow it if it was possible as it sounds like the least amount of work.
2) When editing starts, I'll create a detached copy of the original entity, so that when the edit is cancelled I'd just throw it away and be done. When the edit is confirmed, I copy the detached entity's valued to the original (managed) copy and persist. I see two disadvantages: (a) I need to add code to copy properties between entities, and (b) if there's an error during persisting, the transaction will rollback and I'll end up with a detached, outdated entity which is still contained in the JList.
3) When the uses cancels the edits, I'll detach the edited entity, reload a fresh copy and put it in the original JList instead of the detached one. My problem is that since I've got no experience with JPA yet, I don't know whether this is safe (say that there are references to the edited entity in other entities when I detach it - will these references be properly handled?)
4) Don't modify the entity until the user presses Save. Sounds nice, but doesn't solve the 2)(b) problem.
Which approach is most commonly used? Or is there an even better way?
Thanks.