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