title: Grails one-to-many relationship with index property
body: <p>In my Grails app, I have two domain classes with a one-to-many relationship, e.g.</p>
  
  <pre><code>class Parent    
      static hasMany = [children: Child]
  }
  
  class Child {
      Integer index
      static belongsTo = [parent: Parent]
  }
  </code></pre>
  
  <p>I would like <code>index</code> to record the relative order in which the children were created, such that the first child of a parent will have index 1, the next will have 2, etc. The indices don't have to be consecutive, because a child could be deleted, but they should always reflect the relative order of creation.</p>
  
  <p>I considered doing something like the following to set the <code>index</code> property</p>
  
  <pre><code>class Child {
      Integer index
      static belongsTo = [parent: Parent]
  
      def beforeValidate() {
  
          def maxIndex = Child.createCriteria().get {
              projections {
                  max('index')
              }
              eq('parent', parent)
          }        
  
          this.index = maxIndex + 1 ?: 1
      }
  }
  </code></pre>
  
  <p>But of course this doesn't work because it will assign the same index to two transient <code>Child</code> instances. What is the simplest way to maintain this <code>index</code> property?</p>
  
  <p>FWIW, I'm not too concerned about preventing any other code from setting <code>index</code> but if there is some way to do that, it'd be a bonus.</p>