grails - Grails中的多对多未将记录保存在关系表中

标签 grails many-to-many gorm

我在ColorShade之间有多对多关联。 Color具有许多阴影,而Shades具有许多颜色。

我这样建模:

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表中,后者实际上是两者之间的联接表。

难道我做错了什么?那就是我从docs理解它的方式:

最佳答案

我不确定为什么不填充您的表,但是在this talk中建议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 plugin中看到一个示例类。

关于grails - Grails中的多对多未将记录保存在关系表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941705/

相关文章:

Grails 多个 g :if test for more than one condition

使用 ECTO 和 put_assoc/4 进行多对多

mysql - ActiveJDBC Many2Many 的子表与父表和连接表的架构不同

c# - 在 NHibernate 中使用哪种算法处理多对多关系

grails - Grails:联接不相关表的最佳方法是什么?

grails - 使用 grails criteria api 定义 OR 条件

java - Intellij 中的多模块 Grails 项目

grails - Grails应用程序不会热交换更改

grails - 对象未保存在Spock集成测试中

grails - 在find中调用contains()方法