Last active
August 29, 2015 13:57
-
-
Save fxg42/9925948 to your computer and use it in GitHub Desktop.
Merge, attach or refresh?
This file contains hidden or 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
import gotchas.* | |
// Alice gets the location and saves it to her session... | |
def alice = [:] | |
Location.withNewSession { session -> | |
alice.location = session.get(Location, 1L) | |
session.close() | |
} | |
// Bob gets the location and modifies it... | |
Location.withNewSession { session -> | |
def location = session.get(Location, 1L) | |
location.code = UUID.randomUUID() | |
session.save(location) | |
session.flush() | |
session.close() | |
} | |
// Alice comes back, attaches her location, modifies it, and tries to save it... | |
Location.withNewSession { session -> | |
// Option #1: alice.location = alice.location.merge() | |
alice.location = session.merge(alice.location) //=> throws HibernateOptimisticLockingFailureException | |
alice.location.code = UUID.randomUUID() | |
session.save(alice.location) | |
session.flush() | |
// Option #2: alice.location.attach() | |
session.lock(alice.location, org.hibernate.LockMode.NONE) //=> causes the same exception but gets thrown on call to "flush()" | |
alice.location.code = UUID.randomUUID() | |
session.save(alice.location) | |
session.flush() | |
// Option #3: alice.location.refresh() | |
session.refresh(alice.location) //=> actually seems to work but Hibernate doc says: "It is inadvisable to use this to implement long-running sessions that span many business tasks". | |
alice.location.code = UUID.randomUUID() | |
session.save(alice.location) | |
session.flush() | |
// Option #4: alice.location = Location.get(alice.location.id) | |
alice.location = session.get(Location, alice.location.id) //=> works. | |
alice.location.code = UUID.randomUUID() | |
session.save(alice.location) | |
session.flush() | |
// Option #5: Location.lock(alice.location.id) | |
Location.withTransaction { | |
alice.location = session.get(Location, alice.location.id, org.hibernate.LockMode.UPGRADE) //=> works. | |
alice.location.code = UUID.randomUUID() | |
session.save(alice.location) | |
session.flush() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment