tags:

views:

1820

answers:

2

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?

+1  A: 

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.

Ricardo J. Méndez
+9  A: 

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.

Deepak Mittal
may i ask you a question related to belongsTo?what if i told Player belongsTo Team but I didn't state that Team hasMany Player. if Team were deleted what the happen with Player, are they going to be deleted as well ?
nightingale2k1
@nightingale2k1 - I think if you mapped Team-Player that way there would be no association whatsoever between the two, so a player when the corresponding team is deleted
Don