The difference between session.update() method and the session.lock() method are as below:
Both method save or update() method are intended for reattaching a detached object. session.lock() method simply reattaches the object to the session without checking or updating the data base on the assumption that database in sync with the detached object.
It is the best practice to use either session.update() or session.save or update().
We can 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.
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 "reassociates" them using session.update() or session.save or update().
Example to understand the difference the session.update and session.lock are:
//foo is an instance loaded by a previous Session
foo.setProperty("bar");
session = factory.openSession();
session.saveOrUpdate(foo);
session.flush();
session.connection().commit();
session.close();
You may also call lock() instead of update() and use LockMode.READ (performing a version check, bypassing all caches) if you are sure that the object has not been modified.
Read More →