Example & Tutorial understanding programming in easy ways.

What is the difference between the session.update() method and the session.lock() method?

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().


New Page 1

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 →
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!