title: How do I clear and replace a collection in a one-to-many relationship in Grails/Groovy
body: <p>This question is in two parts, first part is about clearing a list and second part is about assigning an owner to an object.</p>
  
  <p>I have a one-to-many relationship between two domain objects in my model in Grails.  The relationship looks like this...</p>
  
  <pre><code>class Person {
  
      static hasMany = [authorities: Role, locations: Location]
  }
  
  class Location {
  
      static belongsTo = Person
  
  }
  </code></pre>
  
  <p>In my app the <code>locations</code> list on <code>Person</code> gets completely refreshed and replaced with a new list on a user action.  What's more I get the list of <code>Location</code> objects independent of the associated <code>Person</code>.  I resolve which person to apply them to by retrieving the currently logged in user, which I call <code>activePerson</code> and is fine for my purposes.</p>
  
  <p>What I want to do is delete all the existing locations on <code>activePerson</code> and insert all the new ones, associating them with the <code>activePerson</code> as I go.  I have a bunch of properties on <code>Person</code> which I don't want to persist at this point, so I want to avoid saving the whole parent object just because locations children have changed.</p>
  
  <p>I thought of iterating throught the <code>activePerson.locations</code> list and deleting them one by one and relying on GORM/Hibernate to batch the queries together and flush at the end.  This seems like brute force, although it might work.  I was expecting there to be a <code>clearLocations</code> method or something similar, but I can't find one.</p>
  
  <p>If I do just replace the <code>activePerson.locations</code> with a new list and call <code>activePerson.save(flush:true)</code>, will GORM handle the delete of the existing rows?</p>
  
  <p>Secondly I want to put the new <code>Location</code> objects onto <code>activePerson</code>.  Again I could populate the <code>activePerson.locations</code> and save the whole thing, but I would like to avoid that if I can.  I can save them individually, but how do I set <code>belongsTo</code> on each <code>Location</code> object as I go?</p>
  
  <p>So to recap:</p>
  
  <ol>
  <li>How do I clear a list at the many end of a one-to-many collection?</li>
  <li>How do I associate independent objects with a parent object and persist them individually?</li>
  </ol>
  
  <p>Thanks</p>