我正在使用 JPA,并且我有这样的数据结构:
class ContainerA {
long id;
List<ContainerB> bs;
}
class ContainerB {
long id;
List<ContainerC> cs;
}
class ContainerC {
long id;
List<Device> devices;
}
class Device {
long id;
List<Attribute> attributes;
}
class Attribute {
long id;
long value;
}
我需要的是一个查询来获取所有 ContainerA id 的列表,以及它们相应的设备
总数、属性
总数以及所有属性的总和值
;
我是 JPA 新手,我尝试使用 QueryDSL,但没能让它工作。
什么查询是获取我需要的信息的最佳方式?
最佳答案
使用 SQL 来生成此类报告。这更容易,而且我打赌它也会快得多。这是一个非常简单的查询:
SELECT
a.id,
COUNT(DISTINCT d.id) AS Devices,
COUNT(att.id) AS Attributes,
SUM(att.value) AS TotalAttributeValue
FROM ContainerA AS a
LEFT JOIN ContainerB AS b ON a.id = b.a_id
LEFT JOIN ContainerC AS c ON b.id = c.b_id
LEFT JOIN Device AS d ON c.id = d.c_id
LEFT JOIN Attribute AS att ON d.id = att.d_id
GROUP BY a.id
我假设您的架构中只有一对多关系。如果设备和属性之间存在多对多关系,查询可能会更复杂一些。
关于java - 如何获取查询中实体的嵌套列表的总大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45083202/