Search code examples
grailsgroovyormgrails-orm

GORM domain variable without belongsto


What is the different in GORM between

class Books {
  Author author
}

and

class Books {
   static belongsTo = [author: Author]
}

Does cascading rules changes in these two approaches? Also, when to use belongsTo and more importantly, when not to use belongsTo in Grails ?


Solution

  • Yes, belongsTo is intended for controlling cascades of saves and deletes. You may reference the full documentation here http://docs.grails.org/latest/ref/Domain%20Classes/belongsTo.html but to summarize (and in case the URL dies someday):

    • Use belongsTo to indicate ownership. Saves or deletes to the parent will cascade to the child. In your example, if the Author is deleted, his Books will be too (assuming Author hasMany Books
    • Do not use belongsTo if you just want to indicate a relationship with no ownership on either side and no automatic cascading of saves or deletes.