简体   繁体   English

hql查询可获取以父表ID为键,子对象列表为值的地图

[英]hql query to get map with parent table id as key and list of child objects as value

There are two tables parent and child with foreign key relation. 有两个具有外键关系的父表和子表。 Now my requirement is to write hql which return a map with key as parent table id and value as the list of child objects. 现在,我的要求是编写hql,该返回一个映射,其键为父表ID,值为子对象列表。

OK. 好。 You seem to be completely lost, so here's how I would do it: 您似乎完全迷路了,所以这是我的处理方式:

String hql = 
    "select distinct p from Parent p" // get all the parents
    + " left join fetch p.children";  // with their children
List<Parent> parents = session.createQuery(hql).list();

// now transform this list of parents into a Map
Map<Long, List<Child>> result = new HashMap<Long, List<Child>>(parents.size());
for (Parent parent : parents) {
    result.put(parent.getId(), parent.getChildren());
}

Note that I don't really see the point of this map. 请注意,我并没有真正看到这张地图的要点。 If you have the list of parents, each containing its children, the map shouldn't be necessary. 如果您有父母的名单,每个父母都包含其子女,则不需要地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM