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

南楼画角 提交于 2019-11-27 18:22:20

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/654871/grails-gorm-the-meaning-of-belongsto-in-1n-relationships

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!