Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA 2 Criteria API, children count criteria

Tags:

java

jpa

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

like image 826
Anton Shchastnyi Avatar asked Nov 14 '25 17:11

Anton Shchastnyi


1 Answers

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();
like image 54
Anton Shchastnyi Avatar answered Nov 17 '25 08:11

Anton Shchastnyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!