JPA native query result returns duplicate child objects
I have a parent table and a child Table in my DB, and have a OneToMany mapping for them in their corresponding entity classes. The child table has a foreign key parent_id. I am using JPA 2 with Hibernate and MySQL DB.
I wish to retrieve all the parent objects and their corresponding child objects based on some parent property with an SQL Native Query.
For that I have an SqlResultSetMapping as follows:
@SqlResultSetMapping(name="ParentsWithChildren",
entities={ @EntityResult(entityClass = Parent.class),
@EntityResult(entityClass = Child.class)})
I am querying as follows:
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();
On traversing through the result list, I find duplicate child objects for different rows in my child table as shown in the output:
for(Object obj[]: resultList){
Parent parent = (Parent) obj[0];
Child child = (Child) obj[1];
System.out.println("Parent: " + parent + ", Child: " + child);
}
Output:
Parent: Parent@3966c600, Child: Child@1
Parent: Parent@3966c600, Child: Child@1
Parent: Parent@3966c600, Child: Child@1
Parent: Parent@3966c600, Child: Child@1
Parent: Parent@3966c600, Child: Child@1
Parent: Parent@3966c600, Child: Child@1
Parent: Parent@3966c600, Child: Child@1
Parent: Parent@3966c600, Child: Child@1
I don't understand why is this. Is there any way (mapping) to get all the (different) child objects with a native query. Fetching with column names could work and wouldn't require a corresponding object mapping, but I want to fetch all the columns of the child table and hence would prefer to user c.* in the sql query.
I would use a normal HQL query instead of native query. In HQL you can use fetch join:
"select p.*, c.* from parent p left join fetch child c on p.id = c.parent_id where p.property = <some_property>"
With fetch join collections can be initialized along with their parent objects using a single select.
链接地址: http://www.djcxy.com/p/37056.html下一篇: JPA本机查询结果返回重复的子对象