Grails – Quickly examine a domain class associations

July 30, 2013 at 09:00

When your Grails model gets a bit complex, you may find yourself with conflicts in your domain classes associations (I like some parts of GORM, such as dynamic finders, but I think the relationships stuff could be improved).

In my case, I usually end up finding problems when I mix inheritance and different relationships between the same pair of objects (actually, the latter is enough, but also easier to detect), and I have to use the mappedBy option to resolve them.

Anyway, here it goes a simple method to examine the main properties of an association, that reveals such problems (and maybe others) very clearly, so you can be certain that you are actually solving something with the mappedBy, and not just “fishing” (I used to try to “fish” a lot when I was less experienced with Grails):

  def grailsApplication

  def logDomainClassAssociations(Class someDomainClass) {
    grailsApplication.getDomainClass(someDomainClass.name).associations.collectEntries { assoc ->
      [ (assoc.name) : [ 
        'bidirectional', 'circular', 'otherSide.name', 'owningSide',
        'hasOne', 'manyToOne', 'oneToMany', 'manyToMany',
      ].collectEntries { prop ->
        [ (prop) : resolveNestedProperty(assoc, prop) ] 
      }]
    }.each { assocName, assocProperties ->
      log.info "$assocName: $assocProperties" 
    }
  }

This assumes that you declare this method in the a class that contains the all-mighty 😆 nested property resolver method that I posted a few days ago (in my case, I usually create a GrailsUtils class and then declare it as a bean in the resources.groovy file).

Last but not least, the properties that I used are the ones I usually find most useful, but you can adapt it to your needs using the Grails Domain Class API.