2013-02-18 85 views
0

我在ColorShade之间存在多对多关联。 Color有许多色调和Shades有很多颜色。grails中的多对多未在关系表中保存记录

我仿照这个像这样:

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_Shades表保存在记录表ColorShade表,但不这实质上是两者之间的连接表。

我做错了什么? docs这就是我的理解:

回答

1

我不知道为什么你的表没有被填充,但是有一个关于使用这种类型的多对多的性能在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示例类。

+0

我将如何保存与此的关系? – Anthony 2013-02-18 18:14:29

+0

看看Spring安全链接中的'static create()'。实现类似的东西,并调用'ColorShade.create(colorInstance,shadeInstance)'。 – 2013-02-18 18:56:44