简体   繁体   English

计算 Hibernate JPA 中子查询返回的行数

[英]Count number of rows returned by a sub query in Hibernate JPA

I want to do something like the below query in Hibernate JPA.我想在 Hibernate JPA 中执行类似以下查询的操作。

select distinct count(*)
from (
         select distinct entity1.CODE                              as col_0_0_,
                         string_agg(entity2.PRODUCT_IMAGE_URL, ',') as col_1_0_,
                         count(entity1.CODE)                       as col_2_0_
         from entity1
                  inner join entity2 on entity1.id = entity2.entity1_ID                 
         where entity1.id = 1           
         group by entity1.CODE
     ) as cnt;

Any idea how would i do this using Criteria API?知道如何使用 Criteria API 做到这一点吗?

You will need something like the following:您将需要类似以下内容:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = cb.createQuery(Long.class);
Root<Entity1> root = criteriaQuery.from(MyEntity.class);
criteriaQuery.select(criteriaBuilder.countDistinct(entityRoot.get("code")));
Long count = entityManager.createQuery(criteriaQuery).getSingleResult();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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