title: How do you find out if you are inserting duplicate when using Spring Data?
body: <p><em>Libraries</em> - Spring-Data-JPA, Java 8, JUnit-4 (for testing)</p>
  
  <p>I have an entity, let us call it <code>Semaphore</code>. There are multiple machines trying to create an identical row of <code>Semaphore</code>. We only want one of them to succeed. Here is what happens - </p>
  
  <ol>
  <li>The <code>Semaphore</code> row has a primary key, always 1.</li>
  <li>Machine A creates the semaphore and saves it to DB using Spring Data <code>save</code></li>
  <li>Machine B <em>thinks</em> it is creating the semaphore as well and calls save but ends up updating it instead, without the client code knowing about it. I can check for <code>exists</code> but that does not guarantee anything as both machines could check before either of them has created a record.</li>
  <li>The machine that won with the insert will clean out the table when finished with processing.</li>
  </ol>
  
  <p>What choices do we have, other than using the Entity Manager directly to see if the entity is new or not? Essentially override the Spring Data save method.</p>
  
  <p>We use Oracle as the DB.</p>
  
  <p>For everyone's ready reference, here is Spring's <code>SimpleJpaRepository</code> save method.</p>
  
  <pre><code>@Transactional
  public &lt;S extends T&gt; S save(S entity) {
      if(this.entityInformation.isNew(entity)) {
          this.em.persist(entity);
          return entity;
      } else {
          return this.em.merge(entity);
      }
  }
  </code></pre>