简体   繁体   English

HQL - 两个相同查询之间的区别

[英]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.表通常映射到实体 bean 中,所有列都是正确的。

I believe in the second query , the result is a List<Object[]> :我相信第二个query ,结果是一个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;我有这个猜测观察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.查询select tab.col1, tab.col2, tab.col3的结果返回 object 数组的列表,其中包含所选字段,即 col1、col2 和 col3。

Then from the object array, you can extract fields by their index.然后从 object 数组中,您可以按索引提取字段。

for(Object[] field : dataList){

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

}

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

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