I am relatively new to Hibernate framework. I have written the following piece of code and changed the method calls to : save(), saveOrUpdate(), update(), lock() and merge() methods. Surprisingly, I am getting the same result by calling each and every method. The DB is updated with the newly set values in the Emp Objects. I am confused about the usage of these methods. I have gone through the Hibernate Community documentation as well but couldn't understand.
lock(emp1, LockMode.NONE) was used to reassociate a transient instance with a session. If you call update on a detached object it triggers an update whether the object has changed or not. To avoid this lock was used to re associate the instance with a session so this would not happen. Note that lock is now deprecated.
I am trying to grasp the basics of following functions:
Considering the first method i.e. save() method, please refer the code snippet CODE SNIPPET I below.
I. I inserted some data in the DB with empId = 1 and then get this object in emp1 in session instance ssn1. Now, I called ssn1.save(emp1) but it doesn't save the object again into the db nor is any exception thrown. Now, if I open a new session, and then call ssn2.save(emp1), it inserts a new record into the db. Why it is behaving in this manner?
II. Also, I if I call saveOrUpdate(emp1) method on ssn2, then it doesn't insert a new record. Please explain this behavior.
CODE SNIPPET I
CODE SNIPPET II
Considering CODE SNIPPET II, I have the following queries:
saveOrUpdate: It either inserts a new record if one doesn't exist in db or updates the existing one if one with the given id exist in the db. But, how will it behave in case of detached objects?
update : It will reattach the object to the session. Suppose, I get an object say object1 using session1 and then session1 is closed, Now, the object1 is detached. And, I opened a new sessoin session2 and call update with object1 on this session session2, what will happen? What will happen if I call saveOrUpdate in this case rather than update method?
merge: what will happen if I call merge method rather than above two methods in above scenario.
Thanks for your patience and your time. I am really sorry if I am missing on some basics of the topic as I am a learner in this area.
Thanks Bill for your patience and time. I have gone through the link provided but still things are not very much clear to me. Can you please update my sample code so that it produces different results for merge, saveOrUpdate and lock methods and I can visualize the difference among these methods. Thanks again for your time.