Hi,
I have 1-many relationship between 2 tables, Parent and Child. I want to use sql query to get list of all parents with children initialized for each Parent (using left join). For now I want to do it with native sql only.
Code:
SQLQuery sqlQuery = session.createSQLQuery("select * from test_parent p left join test_child c on p.id_parent = c.id_parent");
sqlQuery.addEntity("parent", Parent.class);
sqlQuery.addJoin("child", "parent", "children");
List list = sqlQuery.list();
The result is List<Object[]>. Each Object[] has Parent on 0th and Child instance on 1st. Parent instances are repeated for all children. But Parent.children is initialized properly on each Parent instance. I only want to have a list of Parent as result.
So i need to transform the results using below code.
Code:
Map<Long, Parent> parentsMap = new HashMap<Long, Parent>(results.size());
List<Parent> parents = new LinkedList<Parent>();
for(Object[] resultItem : results) {
Parent parent = (Parent)resultItem[0];
if(!portsMap.containsKey(port.getIdParent())) {
parentsMap.put(parent.getIdParent(), (Parent)resultItem[0]);
parents.add(parent);
}
}
Any idea how to get transformed results directly. Thanks.