HQL - difference between two same queries

感情迁移 提交于 2020-01-06 05:40:08

问题


Why does this query work normal:

Query query = session.createQuery("from Table tab");

And this query:

Query query = session
  .createQuery("select tab.col1, tab.col2, tab.col3 from Table tab");

And that's what I'm doing with both queries:

dataList = query.list();
for (Table item : dataList)
{
  System.out.println(item.getCol1();
}

reports:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to table.Table
at test.TestCriteria.main(TestCriteria.java:35)

Could you help?

Table is normally mapped in entity bean and all the columns are correct.


回答1:


I believe in the second query, the result is a List<Object[]>:

Object[] row = (Object[]) dataList.get(i);
Object col1Value = row[0];
Object col2Value = row[1];
Object col3Value = row[2];

I have this guess observing Ljava.lang.Object; in the exception trace.




回答2:


The result of query select tab.col1, tab.col2, tab.col3 returns list of object array which contains the selected fields i.e col1, col2 & col3.

Then from the object array, you can extract fields by their index.

for(Object[] field : dataList){

    col1 = field[0]; //-- Casting accordingly
     col2 = field[1]; 
     col3 = field[2]; 

}


来源:https://stackoverflow.com/questions/10009854/hql-difference-between-two-same-queries

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