URI / ProjectTrackerMain / milestone / save类java.lang.IndexOutOfBoundsException消息索引:0,大小:0

时间:2017-07-24 14:01:15

标签: grails grails-2.0 grails-controller

当我尝试保存数据时,第一个条目保存,但是当我尝试第二次输入时 它给出错误,这是错误

  

URI:/ ProjectTrackerMain / milestone / save Class   :java.lang.IndexOutOfBoundsException消息:索引:0,大小:0

这是我保存员工里程碑数据的代码。

def save(){
    def milestone=new Milestone(params)
    milestone.save()
    List<Employee> 
    employee=Employee.findAllById(session.getAttribute("empID"))
    EmployeeMilestone employeeMilestone=new EmployeeMilestone()
    employeeMilestone.setEmployee(employee.get(0))
    employeeMilestone.setMilestone(milestone)
    employeeMilestone.save()
    redirect(action: "show",id: employeeMilestone.id)
}

2 个答案:

答案 0 :(得分:0)

employee.get(0) - 为了做到这一点,你必须确保employee.size() >=1 但您的员工名单可能是有效的。在这种情况下,你不能得到元素#0

答案 1 :(得分:0)

代码片段存在很多错误,我会尝试帮助您了解如何以更好的方式完成上述所有操作,以令人困惑的方式编写内容并不会使代码更容易你要调试:

// You are createing a list in which you query Employee.findAll
List<Employee>  employee=Employee.findAllById(session.getAttribute("empID"))

//But inside this list you are only looking for that 1 id.

您的上述列表将始终包含1个元素。你正在使用findById,如果你知道你可以做的id

,那真的不需要
Employee.get(session.getAttribute("empID") as Long)

//You are then creating employeeMilestone 
    EmployeeMilestone employeeMilestone=new EmployeeMilestone()
//Then without checking your 1 list result you are directly attempting to get the first element
    employeeMilestone.setEmployee(employee.get(0))

让我们再试一次:

def save(){
    def milestone=new Milestone(params)
    milestone.save()
    //Do you even have something in your session?
    if (session.getAttribute("empID")) {
        println "yes we have ${session.getAttribute("empID")}"
        Employee employee=Employee.get(session.getAttribute("empID") as Long)
       if (employee) { 
         println "yes we have eployee ${employee?.id}
         EmployeeMilestone employeeMilestone=new EmployeeMilestone()
         employeeMilestone.employee=eployee
         employeeMilestone.milestone=milestone
         employeeMilestone.save()
         redirect(action: "show",id: employeeMilestone.id)
       } else {
         println "No employee found"
       }
     } else {
        println "session could not be found"
     }
}

希望这不会让你第四次尝试一些显然需要花费很长时间才能沉沦的东西

您在操作中重定向代码的事实表明您正在控制器中执行上述所有操作,这甚至是错误的转弯。

服务中的事务性事物是否在控制器中执行控制器操作并查看视图中的内容。