2014-01-21 90 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