title: Spring JPA implementing "save changes" in one call
body: <p>We have a page where the user is able to make changes to an object (ex: company). This object has generic fields (ex: names, dates, etc) and also a few @OneToMany annotations (addresses, phone numbers, etc).</p>
  
  <p>Our requirement is to allow the user to make changes to the frontend and then save these changes after clicking a button. The problem we are facing is with updating the OneToMany relations.</p>
  
  <p>Consider the following scenario:</p>
  
  <p>User makes a change to an existing address (id: 1), they create a new address (no id item) and they delete an existing address (not visible in the request).</p>
  
  <p>Request data that hits the backend:</p>
  
  <pre><code>{
      id: 1,
      name: "Edited company name",
      addresses: [
          {
              id: 1,
              name: "modified address",
              line1: "12 Main street"
          },
          {
              name: "This is a new address without an id",
              line1: "5 Someother Street",
          }
      ]
  }
  </code></pre>
  
  <p>By default we have 2 options:</p>
  
  <p><strong>Option 1:</strong></p>
  
  <p><em>Spring configuration:</em></p>
  
  <pre><code>@OneToMany(fetch = FetchType.LAZY, mappedBy = "company", orphanRemoval = true)
  @Cascade(org.hibernate.annotations.CascadeType.ALL)
  </code></pre>
  
  <p>With this configuration the deleted address is not part of the JSON so the "orphanRemoval" option ensures that all addresses that are not passed in the JSON will be removed. The problem here is that there is no way to specify that only a single address should be removed as opposed to deleting all company addresses that are not part of the JSON. </p>
  
  <p><strong>Option 2:</strong></p>
  
  <p><em>Spring configuration:</em></p>
  
  <pre><code>@OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
  @Cascade(org.hibernate.annotations.CascadeType.ALL)
  </code></pre>
  
  <p>The orphanRemoval option is false here (i.e. not set). So what this means is that the new address is created, the existing address is updated but nothing is deleted.</p>
  
  <p>So my question is this: is there a better/default way to implement this in Spring or do we manually need to keep track of the deleted items and implement our own logic to make sure only the items we want to delete are indeed deleted?</p>
  
  <p>P.S.</p>
  
  <p>I realize this can all be solved by simply making DELETE calls and deleting the address after a button click, but the idea here is that we only make a DB call after the user hits "SAVE" which should send all changes to the server at once. We can't use  DELETE calls because we can't revert those should the user decide to hit "cancel" and not save their changes.</p>