2

问题: GORM 能够以一对多的关系创建(保存)父对象及其子对象。 根据这个文档示例但是我的代码在某个地方是错误的,这使得它不可能。请帮我找到它:|

更新: 发现了一些错误输入的字母。(由于 STS 在我的 PC 上不起作用......)但问题仍然存在。但是,我对抛出异常的建议感到困惑。仍然需要帮助。

父模型:

package tanktactics

class Guide {
    String title
    Date created
    SortedSet chapters

    static hasMany = [chapters: Chapter] //changed to has

    static constraints = {
    }
}

儿童型号:

package tanktactics

class Chapter implements Comparable {
    String title
    String content
    Integer sortOrder
    static belongsTo = [guide: Guide]

    static constraints = {
    }

    int compareTo(obj) {
        sortOrder.compareTo(obj.compareTo) //changed to sort
    }
}

打印输出grails console

import tanktactics.Guide
import tanktactics.Chapter

some_guide = new Guide(title: "First guide!", created: new Date())
some_guide.addToChapters(new Chapter(title: "Ch II", content: "Lorem II", sortOrder:1))
    .addToChapters(new Chapter(title: "Ch I", content: "Lorem", sortOrder:0))
    .save()

some_guide.title
some_guide.chapters[0].title
some_guide.chapters[0].content
some_guide.chapters[1].title
some_guide.chapters[1].content

groovy> import tanktactics.Guide 
groovy> import tanktactics.Chapter 
groovy> some_guide = new Guide(title: "First guide!", created: new Date()) 
groovy> some_guide.addToChapters(new Chapter(title: "Ch II", content: "Lorem II", sortOrder:1)).addToChapters(new Chapter(title: "Ch I", content: "Lorem", sortOrder:0)).save() 
groovy> some_guide.title 
groovy> some_guide.chapters[0].title 
groovy> some_guide.chapters[0].content 
groovy> some_guide.chapters[1].title 
groovy> some_guide.chapters[1].content 

Exception thrown

groovy.lang.MissingMethodException: No signature of method: tanktactics.Guide.addToChapters() is applicable for argument types: (tanktactics.Chapter) values: [tanktactics.Chapter : null]
Possible solutions: addToChapters(java.lang.Object), getChapters()
    at com.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:963)
    at com.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1237)
    at temp_test.run(temp_test.groovy:6)
    at com.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1237)
    at com.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1237)
4

2 回答 2

1

看来你在指南课上拼错了。可能您的意思是hasMany而不是 hadMany。

于 2012-04-11T10:48:39.653 回答
1

您还应该将此代码放入您的域类(以及具有 hasMany 属性的所有其他类中):

static mapping = {
    chapters(cascade:"all-delete-orphan")
}
于 2012-04-11T10:54:58.687 回答