java - hql 查询获取以父表 id 作为键、以子对象列表作为值的映射

标签 java dictionary hql

有两个具有外键关系的表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/

相关文章:

java - 如何编写 SQL 语句 - hibernate/persistence 查询异常 - 无法解析属性

Java SQL 查询 - Hibernate

hibernate - org.hibernate.QueryException : illegal attempt to dereference collection

java - 提取自增主键的标准做法是什么?

使用 ReaderWriterLockSlim 的 C# 字典

java - Android 中的 SQLite 删除查询

c++ - STL map.find 在使用 vs2010 的调试和发布中表现不同

python - 提取上一级嵌套字典中关联的键

java - Jboss 和 OPEN MQ 集成

java - 管理多个版本的 JDK : invalid source release error