Hello,
I have successfully configured hibernate to write data to a database table, and now I am trying to read from it. I want to get back all of the objects that I originally wrote to a table. I have a class Project with attributes id, name, client and location.
I have saved three of these objects in a MySQL table name PROJECT
My database table "PROJECT" has the columns: id, name, client, location (in that order)
The table I am trying to read has:
ROW1-> id: 1 name: name1 client: client1 location: location1
ROW2-> id: 2 name: name2 client: client2 location: location2
ROW3-> id: 3 name: name3 client: client3 location: location3
I am calling this method to see what happens through each iteration:
Code:
public void listProjects() throws Exception {
// Create SessionFactory and Session objects
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
//Query using Hibernate Query Language
String hqlString = "FROM Project as p";
Query query = session.createQuery(hqlString);
//Iterate through stored objects
for (Iterator it = query.iterate(); it.hasNext();) {
Project tempProjObj = (Project) it.next();
System.out.println("Name: " + tempProjObj.getName());
System.out.println("Client: " + tempProjObj.getClient());
System.out.println("Location: " + tempProjObj.getLocation());
}
session.close();
}
It's output is the following:
Name: name1
Client: client1
Location: location1
Name: name2
Client: client2
Location: location2
Name: name3
Client: client3
Location: location3
Exception in thread "main" java.lang.NullPointerException
at beans.Tester.main(Tester.java:11)
As you can see, it managed to read all of the rows and get the appropriate values, but still throws a NullPointerException as if it's going for a fourth row. I'd like to find a way to prevent this. Is there a reason why Iterator it.hasNext() is returning true even if the next row doesn't exist? Are there other methods I can call to test for the existance of further rows?
Thank you all for any suggestions!