Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails/GORM: The meaning of belongsTo in 1:N relationships

In an ordinary one-to-many mapping the "one"-side is the owner of the association. Why would anyone use the belongsTo-mapping for such a mapping? Am I missing some side-effect of specifying belongsTo?

In other words: what are the effects of specifying a belongsTo-mapping in GORM vs. not specifying it?

like image 603
knorv Avatar asked Mar 17 '09 15:03

knorv


2 Answers

Whether to specify belongsTo depends upon the type of referential action you want.

If you want Grails to do On Delete, CASCADE referential action, then DO specify belongsTo. If you want Grails to do On Delete, RESTRICT referential action, then DON'T specify belongsTo.

e.g.

// "belongsTo" makes sense for me here. 
class Country {
  String name
  static hasMany = [states:State]
}

class State {
  String name;
  // I want all states to be deleted when a country is deleted. 
  static belongsTo = Country
}

// Another example, belongsTo doesn't make sense here
class Team {
  String name
  static hasMany = [players:Player]
}

class Player {
   String name
   // I want that a team should not be allowed to be deleted if it has any players, so no "belongsTo" here. 
}

Hope this helps.

like image 146
Deepak Mittal Avatar answered Nov 14 '22 09:11

Deepak Mittal


Specifying belongsTo allows Grails to transparently cascade updates, saves and deletes to the object's children. Without belongsTo, if you attempt to delete a master record, you'll end up getting a foreign key violation if it has any details it owns.

like image 2
Ricardo J. Méndez Avatar answered Nov 14 '22 09:11

Ricardo J. Méndez