How to populate JTable using Hibernate?

2019-08-18 03:45发布

问题:

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

回答1:

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:

  1. create an empty table model outside the loop
  2. in the loop you add new rows of data to the model.
  3. when the loop finishes, you create the table with your model.

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);


回答2:

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.