title: Is there a way to save an @Entity with pre-defined @EmbeddedId value using Spring Data's CrudRepository#save() method?
body: <p>I'm creating a new service with the goal of consuming Kafka events in an idempotent manner and storing the data into a new PostgreSQL database.</p>
  
  <p>The event will provide data which will be used in the composite key:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Embeddable
  public class MyCompositeKey implements Serializable {
  
      @Column(name="field1", nullable = false)
      private UUID field1;
  
      @Column(name="field2", nullable = false)
      private UUID field2;
  
      @Column(name="field3", nullable = false)
      private UUID field3;
  
  ... boilerplate Constructors/getters ...
  </code></pre>
  
  <p>And the Entity will be referencing it via <code>@EmbeddedId</code>:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Entity
  @Table
  public class MyEntity implements Serializable {
  
    @EmbeddedId private MyCompositeKey myCompositeKey;
  
  ... Columns/Constructors/getters ...
  </code></pre>
  
  <p>When an event is consumed, I want to let <code>spring-data-jpa</code> be smart enough to know whether we are replacing data from an existing MyEntity, or creating a new row.</p>
  
  <p>The logic was deemed safe enough to use the <code>CrudRepository#save</code> method before researching the expectation of the logic within that method:</p>
  
  <pre class="lang-java prettyprint-override"><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>
  
  <p>I've gotten to the point where the transactions appear to be completed, but no records are persisted to the table. </p>
  
  <p>I've confirmed via debugging that the call to <code>#save</code> is branching into the <code>return this.em.merge(entity)</code> logic referenced above.</p>
  
  <p>I've only found one possibly helpful blog post[1] for a similar scenario, and am lost on where to go next after it didn't seem to resolve the issue.</p>
  
  <p>The only other option I can foresee is to manually go through a potential three-query execution:</p>
  
  <ol>
  <li><code>findById</code></li>
  <li>if exists, <code>delete</code></li>
  <li><code>save</code></li>
  </ol>
  
  <h2>Components</h2>
  
  <ul>
  <li>spring-boot-starter 2.0.6</li>
  <li>spring-boot-starter-data-jpa 2.0.6</li>
  <li>hibernate 5.2.x</li>
  </ul>
  
  <h2>References</h2>
  
  <p>[1] <a href="https://jivimberg.io/blog/2018/11/05/using-uuid-on-spring-data-jpa-entities/" rel="nofollow noreferrer">https://jivimberg.io/blog/2018/11/05/using-uuid-on-spring-data-jpa-entities/</a></p>