title: Spring Data / Hibernate save entity with Postgres using Insert on Conflict Update Some fields
body: <p>I have a domain object in Spring which I am saving using JpaRepository.save method and using Sequence generator from Postgres to generate id automatically.</p>
  
  <pre><code>@SequenceGenerator(initialValue = 1, name = "device_metric_gen", sequenceName = "device_metric_seq")
  public class DeviceMetric extends BaseTimeModel {
  
      @Id
      @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "device_metric_gen")
      @Column(nullable = false, updatable = false)
      private Long id;
  ///// extra fields
  </code></pre>
  
  <p>My use-case requires to do an <code>upsert</code> instead of normal <code>save</code> operation (which I am aware will update if the id is present). I want to update an existing row if a combination of three columns (assume a composite unique) is present or else create a new row.
  This is something similar to <a href="http://www.postgresqltutorial.com/postgresql-upsert/" rel="noreferrer">this</a>:</p>
  
  <pre><code>INSERT INTO customers (name, email)
  VALUES
     (
        'Microsoft',
        'hotline@microsoft.com'
     ) 
  ON CONFLICT (name) 
  DO
        UPDATE
       SET email = EXCLUDED.email || ';' || customers.email;
  </code></pre>
  
  <p>One way of achieving the same in Spring-data that I can think of is:</p>
  
  <ol>
  <li>Write a custom save operation in the service layer that</li>
  <li>Does a get for the three-column and if a row is present</li>
  <li>Set the same id in current object and do a repository.save</li>
  <li>If no row present, do a normal repository.save</li>
  </ol>
  
  <p>Problem with the above approach is that every <code>insert</code> now does a <code>select</code> and then <code>save</code> which makes two database calls whereas the same can be achieved by postgres <code>insert on conflict</code> feature with just one db call.
  Any pointers on how to implement this in Spring Data?</p>
  
  <p>One way is to write a native query <code>insert into values (all fields here)</code>. The object in question has around 25 fields so I am looking for an another better way to achieve the same.</p>