2014-01-21 51 views
2

该查询选择。HQL从多个表

然而,当我遍历儿童List我就行了这个循环for (int j = 0; j < allParent.get(i).getAllChild().size(); j++) {得到java.lang.ClassCastException

for (int i = 0; i < allParent.size(); i++) { 
    System.out.println(allParent.get(i)); 
    for (int j = 0; j < allParent.get(i).getAllChild().size(); j++) { 
      System.out.println("Child: " + allParent.get(i).getAllChild().get(j).getID()); 
    } 
    HibernateUtil.getSessionFactory().getCurrentSession().flush(); 
    HibernateUtil.getSessionFactory().getCurrentSession().clear(); 
} 

Parent.hbm.xml

<bag name="allChild" table="child" inverse="true" lazy="true" fetch="select"> 
    <key property-ref="surname"> 
     <column name="surname" not-null="true" /> 
    </key> 
    <one-to-many class="com.test.Child" /> 
</bag> 

有没有一种方法,我可以使用Criteria(或别的东西)来运行此语句,而不是使用它填充allParentListallChildList链接到allParent之内的每个Parent

+0

是child_id字符串变量,如果您显示模型类,它也会对我们更有帮助 – harrybvp

+0

请发布完整的堆栈跟踪。 –

回答

0

没有看到模型类,我最好的猜测就是你想用'AND child.id =:childId'替换'AND child_id =:childId',或者在你的Child类中标记id列。

0

由于您在HQL中使用投影,因此您的结果将会是List。因此,对于每个结果行,根据您的投影,您有一个Object []数组,其数据类型如下。 {字符串,你的模型对象,int/long,字符串}。所以,当你做allParent.get(i).getAllChild()i=0你正在做getAllChild()Object[]阵列,并将导致ClassCastException

请在HQL中使用预测。

+0

有没有一种方法可以使用'Criteria'(或别的东西)来运行这个语句,并让它在'allParent'中填充每个'Parent'链接的'allParent'' List'和'allChild'' List'? – ThreaT

+0

也许我可以配置我的'Parent.hbm.xml'映射不同? – ThreaT

+0

HQL或Criteria你可以通过加入孩子与父母一起获得父母及其所有孩子。在HQL中,让父母单独在投影中迭代父列表。那么你不会期望任何ClassCastException。 – Pokuri