title: Spring Data Rest and collections with unique constraints
body: <p>I'm evaluating spring-data-rest and am running into a situation where the magic no longer appears to be working in my favor.</p>
  
  <p>Say I have a collection of items.</p>
  
  <p>Parent - 1:M - Child</p>
  
  <pre><code>Parent
     Long id
     String foo
     String bar
  
     @OneToMany(...)
     @JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false)
     Collection&lt;Child&gt; items
  
     setItems(items) {
        this.items.clear();
        this.items.addAll(items);
     }
  
  @Table(name = "items", uniqueConstraints = {@UniqueConstraint(columnNames = {"parent_id", "ordinal"})})
  Child
     Long id
     String foo
     Integer ordinal
  </code></pre>
  
  <p>The database has a constraint that children of the same parent can't have conflicting values in one particular field, 'ordinal'.</p>
  
  <p>I want to PATCH to the parent entity, overwriting the collection of children. The problem comes with the default behavior of hibernate. Hibernate doesn't flush the changes from when the collection is cleared until after the new items are added. This violates the constraint, even though the eventual state will not.</p>
  
  <pre><code>  Cannot insert duplicate key row in object 'schema.parent_items' with unique index 'ix_parent_items_id_ordinal'
  </code></pre>
  
  <p>I have tried mapping this constraint to the child entity by using @UniqueConstraints(), but this doesn't appear to change the behavior.</p>
  
  <p>I am currently working around this by manually looking at the current items and updating the ones that would cause the constraint violation with the new values.</p>
  
  <p>Am I missing something? This seems like a fairly common use case, but maybe I'm trying too hard to shoe-horn hibernate into a legacy database design. I'd love to be able to make things work against our current data without having to modify the schema.</p>
  
  <p>I see that I can write a custom controller and service, à la <a href="https://github.com/olivergierke/spring-restbucks" rel="nofollow">https://github.com/olivergierke/spring-restbucks</a>, and this would let me handle the entityManager and flush in between. The problem I see going that way is that it seems that I lose the entire benefit of using spring-data-rest in the first place, which solves 99% of my problems with almost no code. Is there somewhere that I can shim in a custom handler for this operation without rewriting all the other operations I get for free?</p>