grails中的many-to-many不会在关系表中保存记录



我在ColorShade之间有一个多对多的关联。CCD_ 3具有许多色调并且CCD_ 4具有许多颜色。

我已经这样建模了:

class Color {
  static hasMany = [shades: Shade]
  String name
}
class Shade {
  static belongsTo = Color
  static hasMany = [colors: Color]
  String name
}

然而,当我运行以下代码时:

new Color(name: "Red").addToShades(new Shade(name: "light")).save()

它只保存Color表和Shade表中的记录,而不保存在Color_Shades表中,后者本质上是两者之间的联接表。

我做错什么了吗?这就是我从文档中理解它的方式:

我不确定为什么没有填充表,但在本次讨论中,Burt建议您使用这种多对多的性能。解决方案是使用一个中间类:

class ColorShade implements Serializable {
  Color color
  Shade shade
  //implement hashcode & equals!
  //and also implement helpers like removeAll, remove, create and get.
  static mapping = {
    id composite: ['color','shade']
    table 'Color_Shades'
    version false
  }
}

您可以在Spring Security Core插件中看到一个示例类。

最新更新