How to Handle Database Concurrency
How should I handle an event where
- User A Is Editing a Doc
- User 开发者_JAVA百科B Starts editing the same Doc
- User B Saves
- User A Saves - Should fail but what should I handle it? Telling the user the page(or entity) has been saved by someone else doesn't seem enough. The user should know which part of the document/fields have been changed and determine if he want to retry the save or not.
- If its just short fields, I think I can compare them - whats an effective way to compare old & new values in a field?
- If its a long text document, how can I do something like a diff? Or how then should I handle this? Just telling the user someone saved the document after you've opened it does not seem enough?
In most applications it turns that it actually is enough to simply tell the user that the save failed due to another user updating the same data. This is called optimistic concurrency: essentially, you assume that no conflicts will occur, and you handle the situation where a conflict does occur by simply rejecting a second write operation on the same data.
Anything beyond that is custom programming. Your suggestion of offering a diff is specific to your domain. If it's about editing text documents you can use standard diff documents. Before going this route however, ask yourself whether it's really worth spending much time on...
Note sure for which language you want this but in Java I use xstream to serialize the object into xml and then diff the XMLs using http://www.crosswire.org/jsword/java2html/org.crosswire.common.diff.index.html to see what changed.
If you have just a couple of entities and use cases then you can get away by implementing all this behavior manually and only use the diff engine to compare the big blobs of text.
精彩评论