2013-02-18 92 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