问题
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