Reputation: 19
I am getting index out of bound exception while executing this code. Can anyone help me in sorting out this issue.
Session session = new Configuration().configure().buildSessionFactory().openSession();
String sql = "select name from chapter_product where name = 'sample'";
SQLQuery query = session.createSQLQuery(sql);
List results = query.list();
if(results .get(0)!=null) {
System.out.println("value:"+results.get(0));
}else {
System.out.println("no values");
}
Upvotes: 1
Views: 744
Reputation: 26
if(results .get(0)!=null && !results.isEmpty()) {
System.out.println("value:"+results.get(0));
}else {
System.out.println("no values");
}
Upvotes: 0
Reputation: 31
you are trying to access empty list first element in this line.
You need to check for empty then u need to access the objects
Sample code
if(!results.isEmpty()){
System.out.println("value:"+results.get(0));
}
else{
System.out.println("no values");
}
Upvotes: 1
Reputation: 3819
The issue you have is you are trying to access the 0th element from an empty list.
Your check should be :
if (results == null || results.isEmpty()) {
System.out.println("no values");
} else {
// Do your stuff
}
Upvotes: 0
Reputation: 26056
The error is probably thrown here:
List results = query.list();
This means, that there is no such data in your database and the resulting list is empty, so you can't get the first element of it.
Upvotes: 1