Thursday, November 19, 2009

Grails: belongsTo


In Grails hasMany and belongsTo are used to define relationship between objects. There are various other uses of belongsTo.  Trying to capture them here in this short post.
 
Let's take an example, say you have domain class TaskList which had many Task
 
Direction of Access
In class Task if you define belongsTo as
             belongsTo = TaskList
it means that Task object can not access its associated instance of TaskList
If it is defined as
            belongsTo = [taskList: TaskList]
it means that Task object can access its associated instance of TaskList by doing task.taskList
 
Cascading Deletes
Only if belongsTo is defined cascading delete will happen. If TaskList is deleted all Tasks part of that TaskList will be deleted.
 
addTo* method access
For many-to-many relationship, defining belongsTo enables dynamic addTo* method
Extending previous example, say each Task can have multiple Tag and a Tag can be given to multiple Tasks. Defining belongsTo enables addTo* dynamic methods. e.g. task.addToTags(tag)


Blogged with the Flock Browser
Post a Comment