簡體   English   中英

Grails 保存一對多領域模型

[英]Grails save one to many Domain Model

嗨,我是 Grails 新手,在將數據保存到 DomainModel 時遇到了一些問題。

我有 2 個域 Poll 和 Answeroption,它們具有一對多的關系。

我不明白為什么我的對象為空...錯誤消息:無法在空對象上調用方法 save()

PollDomain:打包練習

class Poll {
    static hasMany = [answerOptions: AnswerOption]

    String questionid
    String question
    boolean manyAnswer = false;

    static constraints = {
    }

}

答案選項域:

package exercise

class AnswerOption{

    Integer answerid
    String option
    Integer voted = 0;

    static belongsTo = [poll: Poll]

    static constraints = {
    }
}

投票控制器:

package exercise

class PollController {
    PollService p
    Poll poll
    AnswerOption answerOption

    static allowedMethods = [save: "POST", vote: "GET", delete: "DELETE"]

    def create() {
        respond( new Poll(params))
        [poll: flash.redirectParams]
        [answerOption: flash.redirectParams]
    }

    def save() {
        def response = p.save(params)
        if (!response.isSuccess) {
            flash.redirectParams = response.model
            redirect(controller: "member", action: "create")
        }else{
            redirect(controller: "member", action: "vote")
        }
    }

    def vote() {

    }
}

投票服務:

package exercise
import grails.gorm.transactions.Transactional
import grails.web.servlet.mvc.GrailsParameterMap

@Transactional
class PollService {
    Poll poll
    AnswerOption answerOption

    def save(GrailsParameterMap params) {

        String qid = AppUtil.generateRandomString()
        println(qid)
        def poll = new Poll(questionid: qid, question: params.question, manyAnswer: params.manyAnswer)

        if (poll == null) {
            println("poll is Null")
        }else{
            println("Not Null")
        }

        def response = AppUtil.saveResponse(false, poll)
        if (poll.validate()) {
            poll.save(flush: true)
            if (!p.hasErrors()){
                response.isSuccess = true
            }
        }
        params.list("option").eachWithIndex { item, index ->
            answerOption=  new AnswerOption(answerid: index, option: item, poll:poll).save(flush: true)
        }

        return response
    }

}

我假設您的NullPointerException發生在PollController.save ,您嘗試調用服務的 save 方法:

def response = p.save(params)

這對我來說似乎很奇怪,因為您將 PollService 的依賴聲明為一個簡單的類成員:

PollService p

afaik,默認情況下,Grails 僅按名稱設置依賴項,而不是按類型。 因此,將此特定字段重命名為“pollService”應該會改善您的情況:

class PollController {
    PollService pollService
    ...
    def save() {
        def response = pollService.save(params)
        ...
    }
}

此外,您始終為控制器和服務中的 2 個域類聲明(但不使用)字段,您不需要它,甚至不想要它。 但是,這不是問題的一部分;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM