title: Unique constraint with saveAll from JpaRepository
body: <p>My application receives arrays containing objects, which are mapped to entities and then persisted.</p>
  <p>The object has an id property that is mapped to a column with a unique constraint placed on it. Objects with duplicate ids may be sent to the application.</p>
  <p>I'm using the <code>saveAll</code> method, but it throws during insertion if any of the objects happens to violate the unique constraint.</p>
  <p>Is there an easy way to make it insert all the non-duplicates and ignore the duplicates, or simply update them?</p>
  <p>I've tried overriding hash and equals, but that didn't help.</p>
  <p>This application receives dozens of requests per second and he amount of duplicates I expect to receive is low.</p>
  <p>entity:</p>
  <pre><code>@Table(name = &quot;table&quot;, uniqueConstraints = @UniqueConstraint(columnNames = &quot;natural_id&quot;))
  public class Entity {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
  
      @Column(name = &quot;natural_id&quot;, unique = true)
      private String naturalId;
  
      // ...
  }
  </code></pre>
  <p>repository:</p>
  <pre><code>public interface Repository extends JpaRepository&lt;Entity, Long&gt;, JpaSpecificationExecutor&lt;Entity&gt; {}
  </code></pre>
  <p>saving method:</p>
  <pre><code>void save(List&lt;Entities&gt; entities) {
          try {
              repository.saveAll(entities);
          } catch (Exception e) {
              log.error(&quot;...&quot;);
              throw e;
          }
      }
  </code></pre>
  <p>If I were to change the saving method to:</p>
  <pre><code>    @Transactional
      void save(List&lt;Entities&gt; entities) {
          for (Entities et: entities) {
              try {
                  repository.save(et);
              } catch (Exception e) {
                  log.error(&quot;...&quot;);
              }
          }
      }
  </code></pre>
  <p>Would that make it all happen within a single transaction? I'm worried because the save method usually creates a new transaction every time it is called, and that would make it extremely slow for an application that receives a decent number of requests per second.</p>
  <p>I might ultimately have to query the database before insertion to filter the duplicates out for insertion, and do that again every time a constraint violation exception is caught. It should work, but is quite ugly.</p>