Reputation: 1
I am creating a simple application using Swing and Hibernate. I want to populate into a JTable
, the list returned by HQL query in Hibernate. Please tell me where I am doing wrong.
List<Employee> employee= (List<Employee>)sess.createQuery("from Employee where ID<10").list();
String[] rows= {"Book Tile","Author","Price"};
for(Employee e:employee) {
String[][] cols= {{e.getFirstName(),e.getLastName(),Double.toString(e.getSalary())},};
DefaultTableModel dtm = new DefaultTableModel(cols,rows);
table.setModel(dtm);
}
I expected to find a table containing all rows returned by HQL, but instead i am finding only the last row each time i run my application
Upvotes: 0
Views: 587
Reputation: 324108
but instead i am finding only the last row each time i run my application
That is because you keep creating a new TableModel each time you iterate through the for loop.
What you need to do is:
So the logic would be something like:
DefaultTableModel dtm = new DefaultTableModel(cols, 0);
for(Employee e:employee)
{
String[] row= {e.getFirstName(), e.getLastName(), Double.toString(e.getSalary())};
dtm.addRow( row );
}
table.setModel(dtm);
Upvotes: 1
Reputation: 86
On each iteration you are replacing datamodel instance with other with the current object. Instead you must declare array with list size, after populate it with list resukls and Last, outside of for, create datamodel and asign it to jtable.
Upvotes: 0