我在我的数据库中有一个父表和一个子表,并且在它们相应的实体类中有一个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查询中。
您是否尝试在您的选择查询中添加“distinct”? – 2013-03-15 16:52:06