merge() method in Hibernate

merge(): It merge the detached object data into persistent data.

Lets understand merge() method by example.

Employee table in database

 

Output in Eclipse

Employee table in database,After execution of above program  

  • Before 23rd line, emp1 is in Persistent state and emp2 is in detached state.
  • In 23rd line, merge() method called, it will check whether there is any object associated with session with identifier 1 (empno 1)
  • emp1#1 is already associated with session, so merge() method copies emp2#1 state into emp1#1 object. After 23rd line also emp1 is in persistent state and emp2 is in detached state.
  • Once the transaction is completed, as emp1#1 object data modified, it will hit the update query to the database to update the session data with the database.

What is the difference between merge and update? 

update () : Use update(), when a session does not contain the persistent instance with the same identifier
merge () : Use merge(), Irrespective of the state of a session, if you need to save the modifications at any given time

Posted in hibernate and tagged , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">