Created
November 12, 2012 11:55
-
-
Save marcpalmer/4058955 to your computer and use it in GitHub Desktop.
Hibernate optimist locking code snippet #14
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
book = Book.get(id) | |
… | |
// make some changes to book | |
… | |
// Now we are at a point when the session is flushing/committing… | |
// Obtain lock. If stale, re-load locked and | |
// merge our existing *dirty* properties according to | |
// merge policies: | |
// Changes we've made will overwrite anything new from the DB | |
book = book.lockAndMergeSessionIn() | |
// … or … | |
// Changes to the DB will survive, anything we changed | |
// that did not change in the DB survives also | |
book = book.lockAndMergeDatabaseIn() | |
// … or … | |
// Exactly the values we have for all properties will be used | |
// all values from the DB will be lost even if changed and | |
// they weren't change in this session (coherent "squash" update) | |
book = book.lockAndOverwrite() | |
// … or … | |
// Changes to the DB will survive, anything we also changed | |
// will be lost | |
book = book.lockAndResolve { conflicts, storedInstance -> | |
for (conflict in conflicts) { | |
switch (conflict) { | |
case 'title': | |
storedInstance.title = book.title | |
break | |
case 'author': | |
storedInstance.author = book.author | |
break; | |
case 'genresList': | |
storedInstance.genresList = book.genresList.clone() | |
break; | |
default: | |
log.debug "Conflicting property value: ${conflict}" | |
storedInstance[conflict.name] = storedInstance[name] | |
} | |
} | |
} | |
// … or when we need to know what we have is stale … | |
boolean objectIsStale = book.lockOrFail() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment