4

我在我的數據庫中有一個父表和一個子表,並且在它們相應的實體類中有一個OneToMany映射。子表具有一個外鍵parent_id。我使用Hibernate和MySQL DB的JPA 2。JPA本地查詢結果返回重複的子對象

我希望根據某個父屬性和SQL本機查詢檢索所有父對象及其相應的子對象。

對於我有一個SqlResultSetMapping如下:

@SqlResultSetMapping(name="ParentsWithChildren", 
     entities={ @EntityResult(entityClass = Parent.class), 
        @EntityResult(entityClass = Child.class)}) 

我查詢如下:

String queryString = "select p.*, c.* from parent p left join child c on p.id = c.parent_id where p.property = <some_property>"; 
Query query = entityManager.createNativeQuery(queryString, "ParentsWithChildren"); 
List<Object[]> resultList = query.getResultList(); 

通過結果列表中穿越,我覺得在不同的行具有重複的子對象我子表格如圖所示輸出:

for(Object obj[]: resultList){ 
     Parent parent = (Parent) obj[0]; 
     Child child = (Child) obj[1]; 
     System.out.println("Parent: " + parent + ", Child: " + child); 
} 

輸出:

Parent: [email protected], Child: [email protected] 
Parent: [email protected], Child: [email protected] 
Parent: [email protected], Child: [email protected] 
Parent: [email protected], Child: [email protected] 
Parent: [email protected], Child: [email protected] 
Parent: [email protected], Child: [email protected] 
Parent: [email protected], Child: [email protected] 
Parent: [email protected], Child: [email protected] 

我不明白這是爲什麼。有什麼方法(映射)使用本機查詢來獲取所有(不同的)子對象。 獲取列名可以工作,並不需要相應的對象映射,但我想要獲取子表的所有列,因此更喜歡用戶c。*在sql查詢中。

+0

您是否嘗試在您的選擇查詢中添加「distinct」? – 2013-03-15 16:52:06

回答

0

我會使用正常的HQL查詢而不是本地查詢。在HQL中,您可以使用fetch連接:

"select p.*, c.* from parent p left join fetch child c on p.id = c.parent_id where p.property = <some_property>" 

通過使用單個select可以初始化fetch連接集合及其父對象。

+0

在代碼中有c.parent_id更正了錯字 – dumbcoder 2013-03-16 11:49:15

+0

爲什麼要使用本機查詢?在HQL中,可以使用fetch連接解決此問題。我修改了答案 – 2013-03-16 17:28:11

+0

我想使用本地查詢,因爲我還想在一個查詢中獲取父項的孫子孫子和孫子孫子等.HQL/JPQL給出了例外:「不能同時獲取多個包」取。 – dumbcoder 2013-03-19 06:34:30