11.3.3. Detached objects and automatic versioning
Each interaction with the persistent store occurs in a new
Session
. However, the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session
and then reattaches them using Session.update()
, Session.saveOrUpdate()
, or Session.merge()
.
// foo is an instance loaded by a previous Session foo.setProperty("bar"); session = factory.openSession(); Transaction t = session.beginTransaction(); session.saveOrUpdate(foo); // Use merge() if "foo" might have been loaded already t.commit(); session.close();
Again, Hibernate will check instance versions during flush, throwing an exception if conflicting updates occurred.
You can also call
lock()
instead of update()
, and use LockMode.READ
(performing a version check and bypassing all caches) if you are sure that the object has not been modified.