title: Updating multiple many-to-one nested entities with Spring Data REST
body: <p>I have a Spring Data REST application with Hibernate as a persistence layer. I have an entity with two different <code>@ManyToOne</code> references. This is my mapping:</p>
  
  <pre><code>@Entity
  public class Menu {
  
      @Id
      @GeneratedValue
      private Long id;
  
      @ManyToOne
      private Menu parent;
  
      @ManyToOne
      private Resource resource;
  
  }
  </code></pre>
  
  <p>I have several Spring Data repositories:</p>
  
  <pre><code>public interface MenuRepository extends CrudRepository&lt;Menu, Long&gt; {}
  
  public interface ResourceRepository extends CrudRepository&lt;Resource, Long&gt; {}
  </code></pre>
  
  <p>I want to link the <code>parent</code> and <code>resource</code> references of a <code>Menu</code> entity instance to existing entities. I send the following requests:</p>
  
  <pre><code>PUT http://localhost:8080/menus/2/resource
  {"_links":{"self":"http://localhost:8080/api/resources/2"}}
  
  PUT http://localhost:8080/menus/2/parent
  {"_links":{"self":"http://localhost:8080/api/menus/1"}}
  </code></pre>
  
  <p>The problem is, only one (random one) of the references gets attached, another stays <code>null</code>.</p>
  
  <p><strong>Reason:</strong></p>
  
  <p>Judging by the Hibernate SQL logs, both update queries generated by Hibernate under the hood update all of the fields, even those that were not changed, and these concurrent updates overwrite each other:</p>
  
  <pre><code>update menu set parent_id=1, resource_id=null where id=2
  update menu set parent_id=null, resource_id=2 where id=2
  </code></pre>
  
  <p><strong>Workaround:</strong></p>
  
  <p>If I add a <code>@DynamicUpdate</code> annotation to the entity, the generated SQL is limited to only changed properties:</p>
  
  <pre><code>update menu set resource_id=2 where id=2
  update menu set parent_id=1 where id=2
  </code></pre>
  
  <p>This solves the problem. But it seems like a very brittle and obscure solution.</p>
  
  <p><strong>My questions:</strong></p>
  
  <ol>
  <li><p>Is there any other (preferably, transactional) idiomatic solution to
  the problem of updating multiple nested references using Spring Data
  REST, without having to send two separate HTTP requests?</p></li>
  <li><p>If I use two separate PUT requests, I expect them to be idempotent,
  and the idempotency should be handled by the REST layer, regardless
  of the underlying persistence layer. The idempotency is obviously
  violated in this case. Is this a bug/feature of Spring Data REST,
  Hibernate, or combination of the two?</p></li>
  <li><p>Maybe I'm missing something else, or some other solution, and this isn't supposed to happen at all?</p></li>
  </ol>