有两个具有外键关系的表parent和child。现在我的要求是编写 hql,它返回一个映射,其中键作为父表 id,值作为子对象列表。
最佳答案
好的。你似乎完全迷失了,所以我会这样做:
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());
}
请注意,我并没有真正明白这张 map 的意义。如果您有 parent 列表,每个 parent 都包含其 child ,则不需要 map 。
关于java - hql 查询获取以父表 id 作为键、以子对象列表作为值的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016539/