title: Grails command object data binding
body: <p>Grails has <a href="http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.1.6%20Data%20Binding">very good support</a> for binding request parameters to a domain object and it's associations. This largely relies on detecting request parameters that end with <code>.id</code> and automatically loading those from the database.</p>
  
  <p>However, it's not clear how to populate the associations of a command object. Take the following example:</p>
  
  <pre><code>class ProductCommand {
  
      String name
      Collection&lt;AttributeTypeCommand&gt; attributeTypes 
      ProductTypeCommand productType
  }
  </code></pre>
  
  <p>This object has a single-ended association with <code>ProductTypeCommand</code> and a many-ended association with <code>AttributeTypeCommand</code>. The list of all attribute types and product types are available from an implementation of this interface</p>
  
  <pre><code>interface ProductAdminService {
      Collection&lt;AttributeTypeCommand&gt; listAttributeTypes();
      Collection&lt;ProductTypeCommand&gt; getProductTypes();
  }
  </code></pre>
  
  <p>I use this interface to populate the product and attribute type selection lists in a GSP. I also dependency-inject this interface into the command object, and use it to "simulate" <code>attributeTypes</code> and <code>productType</code> properties on the command object</p>
  
  <pre><code>class ProductCommand {
  
      ProductAdminService productAdminService
  
      String name   
  
      List&lt;Integer&gt; attributeTypeIds = []
      Integer productTypeId
  
      void setProductType(ProductTypeCommand productType) {
          this.productTypeId = productType.id
      }
  
      ProductTypeCommand getProductType() {
          productAdminService.productTypes.find {it.id == productTypeId}        
      }
  
      Collection&lt;AttributeTypeCommand&gt; getAttributeTypes() {
  
          attributeTypeIds.collect {id -&gt;
              productAdminService.getAttributeType(id)
          }
      }
  
      void setAttributeTypes(Collection&lt;AttributeTypeCommand&gt; attributeTypes) {
          this.attributeTypeIds = attributeTypes.collect {it.id}
      }
  }
  </code></pre>
  
  <p>What actually happens is that the <code>attributeTypeIds</code> and <code>productTypeId</code> properties are bound to the relevant request parameters and the getters/setters "simulate" <code>productType</code> and <code>attributeTypes</code> properties. Is there a simpler way to populate the associations of a command object? </p>