我正在尝试实现类似的东西:
SELECT c.*, asCount.assetCount
FROM Company c
LEFT JOIN (
SELECT company_id, COUNT(*) as assetCount
FROM Asset
GROUP BY company_id) asCount
ON c.id = asCount.company_id
问题:如何使用 JPA 2 Criteria 实现这一点?
我能够单独获得 asCount 结果,但不知道如何将其加入公司
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = builder.createTupleQuery();
Root<Asset> asset = cq.from(Asset.class);
cq.multiselect(asset.<Company>get("company").<Long>get("id").alias("id"), builder.count(asset).alias("assetCount"));
cq.groupBy( asset.<Company>get("company").<Long>get("id") );
Query query = em.createQuery(cq);
List<Tuple> results = query.getResultList();
提前致谢。
PS
1. 有一个类似的线程使用 Hibernate API 询问子项计数:
Hibernate children count criteria
2. 描述该主题的另一个有用线程:JPA CriteriaBuilder - 按一对多关系中关联实体的数量排序