title: Spring boot JPA save with custom primary key
body: <p>How to save an entity with custom primary key?</p>
  <p>For example, I have an entity like below:</p>
  <pre><code>@Entity
  @Table(name = &quot;customer&quot;)
  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  public class Customer {
    @EmbeddedId
    private CustomerCompositeKey identity;
    private String otherdata;
  }
  @Embeddable
  @Data
  @AllArgsConstructor
  @NoArgsConstructor
  public class CustomerCompositeKey implements Serializable {
    @Column(name = &quot;key_one&quot;)
    private String keyOne;
    @Column(name = &quot;key_two&quot;)
    private String keyTwo;
    
     @Override
      public boolean equals(Object o) {
        if (this == o) {
          return true;
        }
        if (!(o instanceof CustomerCompositeKey)) {
          return false;
        }
        CustomerCompositeKey that = (CustomerCompositeKey) o;
        return Objects.equals(keyOne, that.keyOne) &amp;&amp; Objects
            .equals(keyTwo, that.keyTwo));
      }
  
      @Override
      public int hashCode() {
        return Objects.hash(keyOne, keyTwo);
      }
  
  }
  </code></pre>
  <p>Repository class:</p>
  <pre><code>@Repository
  public interface CustomerRepository extends
      JpaRepository&lt;Customer, CustomerCompositeKey&gt; {
  }
  </code></pre>
  <p>Currently, if I simply save I am getting a unique constraint exception. So I modified the code with a select update like below. Save code:</p>
  <pre><code>@Transactional
  public void saveCustomer(CustomerBO customer){
    Optional&lt;Customer&gt; customer = customerRepository.findById(customerCompositeKey);
  if(customer.isPresent()) {
  
  }else{
  }
  customerRepository.save(customer);
  }
  </code></pre>
  <p>This is increasing my latency while saving. Is there any other way to just save without a select query? this block will be executed concurrently.
  <code>customerRepository.save(customer)</code> is already having select/update. But why am I getting a unique constraint error?</p>