一对多和一对一的Grails 2.2.4

时间:2013-09-05 08:32:22

标签: grails one-to-many one-to-one

我想为学生写一个测试应用程序。所以有两种类型。 Question包含许多Answer和正确答案。所以我有一对多和一对一都是双向的。

class Question extends Entity {

    static hasOne   = [ acceptedAnswer: Answer ]

    static hasMany  = [ answers: Answer ]
    static mappedby = [ answers: 'parentQuestion' ]

    static constraints = {
        acceptedAnswer unique: true
    }
}

class Answer  extends Entity {

    Question accesptedInQuestion

    //one of many answers
    static belongsTo = [ parentQuestion: Question] // when ANSWER bidirectional

    static constraints = {
    }
}

抽象实体是:

package com.medreactor.content.model

import org.bson.types.ObjectId

abstract class Entity {

    ObjectId post_id
    String posType  // Question OR ANSWER

    static mapping = {
        id column: 'post_id'
    }
}

我一直收到错误:

grails> run-app 
| Running Grails application
| Error 2013-09-05 10:30:50,805 [localhost-startStop-1] ERROR context.ContextLoader  - Context initialization failed
Message: Error creating bean with name 'pluginManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.codehaus.groovy.grails.exceptions.GrailsDomainException: Property [answers] in class [class com.medreactor.content.model.Question] is a bidirectional one-to-many with two possible properties on the inverse side. Either name one of the properties on other side of the relationship [question] or use the 'mappedBy' static to define the property that the relationship is mapped with. Example: static mappedBy = [answers:'myprop']

有什么问题?我正在映射答案,为什么编译器看不到这个?我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

尝试喜欢这个

Question.groovy

    class Question extends Entity{
         Answer acceptedAnswer
         static hasMany = [answers: Answer]
         static mappedBy = [answers: "parentQuestion"]
         static mapping = {
            answers cascade: 'all-delete-orphan'
         }
         static constraints = {
            acceptedAnswer unique: true
         }
    }

Answers.groovy

class Answer extends Entity {
    Question acceptedInQuestion
    Question parentQuestion

    static constraints = {
        acceptedInQuestion unique: true
    }
}

答案 1 :(得分:0)

1.您的第一个案例是为了修复您使用相同名称的问题实例和问题所以您必须重命名吗?在一对多中,即使是可读的,也必须引用问题

class Answer extends Entity{

        Question question   

        //one of many answers
        static belongsTo = [ questions:Question] // when ANSWER bidirectional // renamed

        static constraints = {
        }
    }

第二

class Question extends Entity {

    /*static hasOne   = [ acceptedAnswer: Answer ] you dont need this , you already said belongs to */
    Answer acceptedAnswer;

    static hasMany  = [ answers: Answer ]
    static mappedby = [ answers: 'parentQuestion' ] //parentQuestion Table

    static constraints = {
        acceptedAnswer unique: true
    }
}

第三次。并且给予一些信任,谢谢!