为什么列表的值在发送到服务时会发生变化

时间:2014-03-21 08:31:04

标签: grails grails-domain-class grails-controller

我是grails的新手,正在开发一个Web应用程序。

我有一个长值列表,它来自Domain类对象的ID。

最初这个列表就像[1,2,3]。我需要在服务类中使用此值列表来保存关联。

但同样的List正在服务类中[49,50,51]

为什么会出现这种48的差异?以及如何将List与我发送的相同。

控制器类:

def createQuestion(CreateQuestionCommand createQuestionCmd) { 
  if( createQuestionCmd.hasErrors() ) { 
    render(view:"create_question", model:[createQuestionCmd:createQuestionCmd , tags:Tag.list()]) 
  } else { 
    Question question = new Question() 
    question.title=createQuestionCmd.title 
    question.description=createQuestionCmd.description 
    List tags= createQuestionCmd.tags 
    question = questionService.create(question,tags) 
    render(view: "question_submitted") 
  } 
}

服务类:

def create(Question question, List<Long> tagId) { 
  List<Tag> tagList=getTagsById(tagId) 
  question.save( failOnError:true ) 
  Iterator itr=tagList.iterator(); 
  while(itr.hasNext()) { 
     Tag tag=itr.next() 
     question.addToTags(tag).save() 
  }
}

def getTagsById(List tagId){ 
  Iterator itr=tagId.iterator(); 
  List<Tag> tags 
  while(itr.hasNext()) { 
    long id=itr.next() 
    println "value of id is : " 
    println id 
    println id.getClass().getName() 
    Tag tag=Tag.findById(id) 
    tags.add(tag) 
  } 
  return tags 
}

2 个答案:

答案 0 :(得分:4)

CreateQuestionCmd.tags为List<String>,您正试图将其置于List<Long>

答案 1 :(得分:1)

只需将对象传递给服务并创建问题对象。在groovy中我们以map格式创建对象。仅在java中,我们需要迭代器来循环集合。在groovy中我们使用每个闭包来循环集合。尝试一下就可以了。以下代码中的任何问题都告诉我。我会帮忙。

控制器类:

def createQuestion(CreateQuestionCommand createQuestionCmd) { 
  if(createQuestionCmd.hasErrors() ) { 
    render(view:"create_question", model:[createQuestionCmd:createQuestionCmd , tags:Tag.list()]) 
  } else { 
    questionService.create(createQuestionCmd) 
    render(view: "question_submitted") 
  } 
}

服务类:

def create(def createQuestionCmd) { 
   def question = new Question(title:createQuestionCmd.title,description:createQuestionCmd.description) 
   question.save(flush:true)    
   List tagIds= createQuestionCmd.tags 
   tagIds.each{
      def tag=Tag.findById(id) 
      question.addToTags(tag).save(flush:true) 
   }
}