title: Why does Hibernate perform INSERT instead of UPDATE when existing value is null?
body: <h1>The Problem</h1>
  
  <p>I observed a constraint violation when merging one of my Hibernate entities. There are two tables A and B, where one holds metadata and the other is a mapping of String values.</p>
  
  <p>In table B there is a combined primary key on (id, key).</p>
  
  <p>Now, when I merge an existing instance of A (that also has several entries for B), Hibernate will perform both UPDATE and INSERT statements for B.</p>
  
  <p>The UPDATE statements are no problem, but the INSERT statement cannot be performed, because it causes a constraint violation, since (id, key) is a unique combination.</p>
  
  <p>I figured out that <strong>this problem only occures, when the existing value in B is <code>null</code></strong>.</p>
  
  <p>I'm on Oracle 11, JPA 2.1 and EJB 3.2. Not entirely sure, how to determine the Hibernate version, though.</p>
  
  <h1>An Example</h1>
  
  <p>Let us assume these are entries of table B:</p>
  
  <pre><code>23, fooKey, foo
  23, barKey, bar
  23, errorKey, null
  </code></pre>
  
  <p>Now when I merge A (id = 23), UPDATE statements will be performed for <code>fooKey</code> and <code>barKey</code>. For <code>errorKey</code>, however, Hibernate will issue an INSERT statement instead and cause a constraint violation.</p>
  
  <p>So my questions are:</p>
  
  <ol>
  <li>Why does Hibernate perform an INSERT statement, when the existing value is <code>null</code>?</li>
  <li>How can I fix this problem?</li>
  </ol>
  
  <h1>My Database</h1>
  
  <p><strong>Table A (</strong> id, version, lastUpdate <strong>)</strong></p>
  
  <p><strong>Table B (</strong> id, key, value <strong>)</strong></p>
  
  <h1>My Entity</h1>
  
  <pre><code>@Entity
  public class A {
    @Id
    public long id;
    public long version = 0;
    public Date lastUpdate = new Date();
  
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "B", joinColumns = @JoinColumn(name = "ID"))
    @MapKeyColumn(name = "KEY")
    @Column(name = "VALUE", length = 2000)
    public Map&lt;String, String&gt; myMapping = new HashMap&lt;String, String&gt;();
  
    // Setters and getters...
  }
  </code></pre>