简体   繁体   English

如何使用Hibernate填充JTable?

[英]How to populate JTable using Hibernate?

I am creating a simple application using Swing and Hibernate. 我正在使用Swing和Hibernate创建一个简单的应用程序。 I want to populate into a JTable , the list returned by HQL query in Hibernate. 我想填充到一个JTable ,该列表由Hibernate中的HQL查询返回。 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 我希望找到一个包含HQL返回的所有行的表,但是每次我运行我的应用程序时,我只会找到最后一行

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. 这是因为每次迭代for循环时,您都会继续创建新的TableModel。

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. 在每次迭代中,您都将使用当前对象将datamodel实例替换为其他实例。 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. 取而代之的是,您必须使用列表大小声明数组,然后用列表结果和最后一个填充(在for之外)创建数据模型并将其分配给jtable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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