2013-10-11 32 views
0

我有2個域類:Category和CatAttribute,它們具有多對一的關係,Category有2個CatAttribute列表。addTo無法添加

class Category { 

    static constraints = { 
     description nullable: true 
     name unique: true 
    } 


    static hasMany = [params:CatAttribute, specs:CatAttribute] 
    static mappedBy = [params: "none", specs: "none"] 
    static mapping = { 
    } 

    List<CatAttribute> params //required attributes 
    List<CatAttribute> specs //optional attributes 
    String name 
    String description   


} 

和我CatAttribute類:

class CatAttribute { 

    static constraints = { 
    } 
    static belongsTo = [category: Category] 
    String name 

} 

當我試圖創建新的對象,它無法保存:

def someCategory = new Category(name: "A CATEGORY") 
.addToSpecs(new CatAttribute(name: "SOMETHING")) 
.addToParams(new CatAttribute(name: "onemore attribute")) 
.save(flush: true, failOnError: true) 

您這兒上課的是簡化/數據嘲笑僅用於說明目的,真正的生產代碼要複雜得多,但兩個領域之間的關係是相同的。在.addToSpec線發生

驗證錯誤:

Field error in object 'Category' on field 'specs[0].category': rejected value [null]; 

此錯誤有與我把CatAttribute對象2列出了在同一個域中Category,如果我刪除或者那些和我對象的創建進行,一切都很完美,我映射域名類Category的方式都基於grails ref ,所以我不認爲映射有什麼問題,但如果有,請告訴我。

+0

你上面顯示的是2'一對多'關係而不是'多一對'的例子。 – dmahapatro

+0

@dmahapatro任何方式使這項工作? – 16dots

+0

你需要CatAttribute的反向引用嗎? –

回答

0

你真的需要關聯List(你是否索引),默認情況下他們是Set。如下
修改類別,你應該是好的:

class Category { 
    String name 
    String description 

    static hasMany = [params: CatAttribute, specs: CatAttribute] 
    static mappedBy = [params: "category", specs: "category"] 

    static constraints = { 
     description nullable: true 
     name unique: true 
     params nullable: true //optional 
    } 
} 

如果你需要一個1:M的關係。

+0

如果我改變了我的mappedBy,它將不可編譯,新的錯誤: 由MappingException引起:實體映射中的重複列:CatAttribute列:category_id(應該使用insert =「false」update =「false」 ) – 16dots

+0

@ 16dots您是否刪除了'List params'和'List specs'?哪個版本的Grails? – dmahapatro

+0

不幸的是我需要他們兩個作爲列表,因爲對象必須按順序排列。所以我猜這是沒有辦法的? – 16dots