21. Explain update(), saveOrUpdate(), lock(), merge()


Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. In other words, update() is usually the first method you would call in a fresh session, ensuring that the reattachment of your detached instances is the first operation that is executed.

The update(), lock() and saveOrUpdate() methods are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

How would you reatach detached objects to a session when the same object has already been loaded into the session?

Use merge() if you want to merge your modifications at any time without consideration of the state of the session.


No comments:

Post a Comment