Skip to content

Instantly share code, notes, and snippets.

@marcpalmer
Created November 12, 2012 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcpalmer/4058955 to your computer and use it in GitHub Desktop.
Save marcpalmer/4058955 to your computer and use it in GitHub Desktop.
Hibernate optimist locking code snippet #14
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