2017-07-24 102 views
0

當我試圖保存數據第一條目保存但當我嘗試第二條目 它給出錯誤,這是錯誤的URI/ProjectTrackerMain /里程碑/保存類java.lang.IndexOutOfBoundsException消息索引:0,大小:0

URI:/ ProjectTrackerMain /里程碑/保存 類別: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) 
} 
+0

可能的重複[關於將數據保存到grails數據庫](https://stackoverflow.com/questions/45095609/about-saving-data-into-grails-databse) – Daniel

+0

這只是https:// stackoverflow.com/questions/45095609/about-saving-data-into-grails-databse你已經接受了答案。 – Daniel

+0

正確地格式化文本 – litelite

回答

0

employee.get(0) - 爲了做到這一點,你必須確保employee.size() >=1 ,但它可能是你的員工名單emply。在這種情況下,您無法獲取元素#0

0

代碼片段有太多錯誤,我會盡力幫助您理解如何以更好的方式將所有上述內容寫入,以令人困惑的方式編寫內容isn不會讓你更容易調試:

// 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個元素。您正在使用的,如果你知道ID真的不需要findById你可以做

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" 
    } 
} 

希望這不會使其向的第四嘗試你問一些顯然需要很長時間才能下沉的東西

你在動作中重定向代碼的事實表明你正在控制器中執行上述所有操作,這是更進一步的錯誤轉向。

在服務器中做事務性的東西在控制器中做控制器的東西,並查看東西的視圖。

相關問題