Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

indexoutofboundsexception - About saving data into grails databse

This my project code I want to save my data into database.

def save(){
    List<Employee> list = Employee.findAllById(session.getAttribute("empId"))
    Milestone milestone = new Milestone()
    milestone.setMilestone_Date(params.milestone_Date)
    milestone.setMilestone_Name(params.milestone_Name)
    milestone.setMilestone_Description(params.milestone_Description)
    milestone.save()
    EmployeeMilestone employeeMilestone=new EmployeeMilestone()
    Employee employee = list.get(0)
    employeeMilestone.setEmployee(employee)
    employeeMilestone.setMilestone(milestone)
    employeeMilestone.save()
    [employeeMilestones:employeeMilestone]
}

I am getting this error

Error 500: Internal Server Error URI /ProjectTrackerMain/milestone/save Class java.lang.IndexOutOfBoundsException Message Index: 0, Size: 0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You didn't actually ask a question, so this may be a bit vague!

An IndexOutOfBoundsException happens when you try to access something from a collection in a location where there is no "something". For example, maybe you asked for the tenth element in a list, but there are only two. In your case, you're asking for the zeroth (in plain English, "First") element on this line of code:

Employee employee = list.get(0)

and presumably the list is empty. Your error message says "Size: 0". You can't get the first element from a list that has zero elements in it, so that's an index out of bounds exception.

Why is your list 0? That's a different question. You might try printing out

session.getAttribute("empId")

to see if your employee ID is what you expected. You might also look at the data in your database to see if you actually managed to save an employee! One way or another, you're not getting the data you expected, and then you're trying to use it.

In general, using a debugger to look at your elements, or just using "println" along the way to look at values is helpful in debugging problems like this. That way, you'll find out on line 1 that your list of Employees is not what you expected, instead of several lines later when you try to use it!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...