title: What is the difference between persist() and merge() in JPA and Hibernate?
body: <p>What is the difference between persist() and merge() in Hibernate?</p>
  
  <p><code>persist()</code> can create a UPDATE &amp; INSERT query, eg:</p>
  
  <pre><code>SessionFactory sef = cfg.buildSessionFactory();
  Session session = sef.openSession();
  A a=new A();
  session.persist(a);
  a.setName("Mario");
  session.flush();
  </code></pre>
  
  <p>in this case <strong>query</strong> will be generated like this:</p>
  
  <pre><code>Hibernate: insert into A (NAME, ID) values (?, ?)
  Hibernate: update A set NAME=? where ID=?
  </code></pre>
  
  <p>so <code>persist()</code> method can <strong>generate</strong> an Insert and an Update.</p>
  
  <p>Now with <code>merge()</code>:</p>
  
  <pre><code>SessionFactory sef = cfg.buildSessionFactory();
  Session session = sef.openSession();
  Singer singer = new Singer();
  singer.setName("Luciano Pavarotti");
  session.merge(singer);
  session.flush();
  </code></pre>
  
  <p>This is what I see in the database:</p>
  
  <pre><code>SINGER_ID   SINGER_NAME
  1           Ricky Martin
  2           Madonna
  3           Elvis Presley
  4           Luciano Pavarotti
  </code></pre>
  
  <p>Now update a record using <code>merge()</code></p>
  
  <pre><code>SessionFactory sef = cfg.buildSessionFactory();
  Session session = sef.openSession();
  Singer singer = new Singer();
  singer.setId(2);
  singer.setName("Luciano Pavarotti");
  session.merge(singer);
  session.flush();
  </code></pre>
  
  <p>This is what I see in the database:</p>
  
  <pre><code>SINGER_ID   SINGER_NAME
  1           Ricky Martin
  2           Luciano Pavarotti
  3           Elvis Presley
  </code></pre>