JPA 2 Criteria API,儿童计数标准

时间:2013-02-27 12:03:18

标签: java jpa criteria

我正在尝试实现类似:

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条件实现此功能?

我可以单独获取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 - sort by the number of associated entities in a one-to-many relationship

1 个答案:

答案 0 :(得分:3)

好的,我自己找到了解决方案。希望它可以帮助别人:)

CriteriaQuery<Tuple> cq = builder.createTupleQuery();
Root<Company> company = cq.from(Company.class);
Join<Company, Asset> secondTable = company.join("assets", JoinType.LEFT);
cq.multiselect(company.<String>get("id").alias("id"), builder.count(secondTable).alias("assetCount"));
cq.groupBy( company.<Long>get("id") );

Query query = em.createQuery(cq);
List<Tuple> results = query.getResultList();