简体   繁体   中英

How to populate JTable using Hibernate?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM