How to populate JTable using Hibernate?

和自甴很熟 提交于 2019-12-25 03:44:11

问题


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.



来源:https://stackoverflow.com/questions/54029937/how-to-populate-jtable-using-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!