HQL - 两个相同的查询 - 在对象类型差异

问题描述:

为什么我必须使用Object[]打印的清单,如果我选择特定的列:HQL - 两个相同的查询 - 在对象类型差异

Session session = DaoSF.getSessionFactory().openSession(); 
List<Object[]> list = new ArrayList<Object[]>(); /* Object[] */ 

Query criteria = session.createQuery(
    "select test.col1, test.col2, test.col3 
    "from Test test " + 
    "group by test.col1, test.col2, test.col3"); 

list = criteria.list(); 

for (Object[] item : list) 
{ 
    System.out.println(item[1] + ", " + item[2] + ", " + item[3]); 
} 

为什么它可以重复同样的选择(选择* - - 不是特定的列)使用原始测试对象?

List<Test> list = new ArrayList<Test>(); /* Test */ 
Query criteria = session.createQuery(
    "from Test test " + 
    "group by test.col1, test.col2, test.col3"); 

list = criteria.list(); 

for (Test item : list) 
{ 
    System.out.println(item.getCol1 + ", " + item.getCol2 + ", " + item.getCol3); 
} 

是否有可能 “转换” Object[]Test对象?

试试这种方法;先在你的Test类中创建一个构造:在查询

public Test(Col1Type col1, Col2Type2 col2, Col3Type col3) { 
    this.col1 = col1; 
    this.col2 = col2; 
    this.col3 = col3; 
} 

现在,你可以说:

select new Test(t.col1, t.col2, t.col3) 
from Test t 

这会给休眠所谓的行映射器构造外面它可以构造Test的对象。那么你将有一个List<Test>query.list()。这种方法有一个问题,你应该为默认提供不同的构造函数,用于不同的可能查询。

+0

你是冬眠大师!它真的有用,谢谢你:-) – gaffcz 2012-04-06 11:38:49

+1

当然。谢谢,但我不是。 – nobeh 2012-04-06 12:06:33

在您的第一个查询中,您返回一行(如列表),由您选择的“测试”对象的几个属性组成。
它不是“测试”对象,所以你不能迭代这种方式。

在您的第二个查询中,您返回“测试”对象:“测试”对象列表,因此您可以迭代为“测试”对象。

+0

谢谢,这很有道理.. – gaffcz 2012-04-07 06:40:26