简体   繁体   中英

HQL - difference between two same queries

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.

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.

The result of query select tab.col1, tab.col2, tab.col3 returns list of object array which contains the selected fields ie 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]; 

}

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