如何计算子查询返回的行数? [英] How do I count the number of rows returned by subquery?

查看:128
本文介绍了如何计算子查询返回的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

select count(*) from (select ...)

(就像在SQL中一样),但是在JPA中.

(As it would be in SQL), but in JPA.

关于我将如何做的任何想法?

Any ideas on how I would do it?

推荐答案

这应该可以解决问题(如果您想使用JPA条件API):

This should do the trick (If you want to use JPA criteria API):

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();  
CriteriaQuery<Long> query = cb.createQuery(Long.class);

Root<Entity> root = query.from(Entity.class);

//Selecting the count
query.select(cb.count(root));

//Create your search criteria
Criteria criteria = ...

//Adding search criteria   
query.where(criteria);

Long count = getEntityManager().createQuery(query).getSingleResult();

另一方面,如果您想使用JP-QL,则以下代码可以解决问题:

On the other hand, if you want to use JP-QL, the following code should do the trick:

//Add the where condition to the end of the query
Query query = getEntityManager().createQuery("select count(*) from Entity entity where...")
Long count = query.getSingleResult();

这篇关于如何计算子查询返回的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆