简体   繁体   中英

JPA 2 Criteria API, children count criteria

I am trying to implement something like:

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

Question: How could I implement this with JPA 2 Criteria?

I am able to get the asCount results separately, but do not know how to join it to the Company

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();

Thanks in advance.

PS
1. There's a similar thread asking children count using Hibernate API: Hibernate children count criteria
2. Another useful thread describing the topic: JPA CriteriaBuilder - sort by the number of associated entities in a one-to-many relationship

Okay, I've found the solution myself. Hope it helps someone else :)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM