If you just want to do it to avoid lazy initialization exceptions, use session.lock(). It has no overhead and generates no database access. But, if your object has changed, this will not be detected by Hibernate and the changes are not stored in the database.
session.refresh() reloads the object from the database and if you have changed anything those changes are lost.
session.update() will update the database. Hibernate assumes that you are calling this method because you have modified it and want to save the changes to the database.
The tricky thing with having objects outside the session is that Hibernates automatic dirty checking mechanism no longer work. So, you need to keep track of changes yourself and call the appropriate method. There is also the session.merge() method which like a combination of session.refresh() and session.update() or session.lock(), except that the original object passed to merge() doesn't become attached to the session. The merge() method instead returns a new object (assuming that the entity really is detached and isn't already in the session).
|