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

旧时模样 提交于 2019-11-29 04:29:17

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.

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.

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