How can I reattach a detached object to a Hibernate Session. The Object has not changed since it was last associated with a (different) Session, so I do not want Hibernate to issue an UPDATE or other SQL statement.
Asked
Active
Viewed 77 times
1
-
Maybe this will help: http://stackoverflow.com/questions/2730388/hibernate-safely-reattach-an-object-to-the-session – Multisync Oct 16 '14 at 22:13
-
@Multisync Thanks. I saw that thread but I didn't see the comment "I think merge() hits the database, which I was hoping to avoid. Note that session.lock(detached_object, LockMode.NONE) does not hit the database at all (if you don't change it after re-attaching it)" ... I will test the lock with LockMode.NONE and report back on what happens. – KyleM Oct 16 '14 at 22:18
-
@Multisync Yep, that works. It also works with the newer/not deprecated LockRequest with LockMode.NONE. – KyleM Oct 16 '14 at 22:24
-
Great, I haven't known that. – Multisync Oct 16 '14 at 22:26
1 Answers
0
parent = new Parent();
parent.setName("NewParent");
Session session = util.getSession();
Transaction trans = session.beginTransaction();
LockRequest r = session.buildLockRequest(LockOptions.NONE);
r.lock(detachedChild);
parent.setChild(detachedChild);
session.save(parent);
trans.commit();
session.flush();
session.close();

KyleM
- 4,445
- 9
- 46
- 78