Your Grails domain class has more properties than you think!

June 10, 2008 – 4:32 pm

But you probably already knew that - things like ‘id’, ‘version’ and ‘log’ properties are added to every Grails domain class by the framework and are pretty obvious.  But there are a few more that might not be so familiar.

Take a look at this domain class:

class Book {
    String name
    Author author
}

Of course, it has a name and author, and a few more - if I print out new Book().properties.each {println it} the following are revealed (check out the one in bold):

  • author:null
  • authorId:null
  • class:class Book
  • constraints:… (removed for brevity)
  • errors:org.springframework.validation.BeanPropertyBindingResult: 0 errors
  • id:null
  • log:org.apache.commons.logging.impl.Log4JLogger@de9e85
  • metaClass:groovy.lang.ExpandoMetaClass@47ec8e[class Book]
  • name:null
  • version:null

I guess I understand where this is coming from (since Book has an Author) - but it tripped me up a little bit the other day when I was working with a domain builder.  The builder is pretty ‘dumb’ - it basically builds domain classes based on attributes of a map that match up with attributes on a domain class.  So along came a new domain class:

class Author {
    String name
    String authorId
}

which just happens to contain an ‘authorId’ (users wanted to capture an ID separately from the ID Hibernate generates).  When the builder checks the properties against the two domain classes - it finds a match in the Book class because of the ‘authorId’ property and tries to set it - but BOOM!  ’authorId’ is a read-only property (as it should be).  No worries, it’s a quick fix - now the builder just checks to see if the property also has a setter - something like if(dc.metaClass.hasProperty(dc, it)?.setter) - and TADA, we’re back up and running.

Anyway, the next time you’re playing around in Grails console - give it a shot and take a look at the properties your domain classes have - you might be surprised what you find.

  1. 2 Responses to “Your Grails domain class has more properties than you think!”

  2. By domain builder you actually mean Grails’ DomainBuilder or a custom builder?

    By Andres Almiray on Jun 12, 2008

  3. It’s a custom builder

    By Mike on Jun 13, 2008

Post a Comment