在JPA 2中,使用CriteriaQuery,如何计算结果 [英] In JPA 2, using a CriteriaQuery, how to count results

查看:167
本文介绍了在JPA 2中,使用CriteriaQuery,如何计算结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JPA 2很新,它是CriteriaBuilder / CriteriaQuery API:

I am rather new to JPA 2 and it's CriteriaBuilder / CriteriaQuery API:

CriteriaQuery javadoc

CriteriaQuery javadoc

CriteriaQuery 在Java EE 6教程中

CriteriaQuery in the Java EE 6 tutorial

我想计算CriteriaQuery的结果而不实际检索它们。这是可能的,我没有找到任何这样的方法,唯一的方法是这样做:

I would like to count the results of a CriteriaQuery without actually retrieving them. Is that possible, I did not find any such method, the only way would be to do this:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();

CriteriaQuery<MyEntity> cq = cb
        .createQuery(MyEntityclass);

// initialize predicates here

return entityManager.createQuery(cq).getResultList().size();

这不是正确的方法......

And that can't be the proper way to do it...

有解决方案吗?

推荐答案

MyEntity类型的查询将返回 MyEntity 。您需要查询 Long

A query of type MyEntity is going to return MyEntity. You want a query for a Long.

CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();

显然,您希望使用示例中跳过的任何限制和分组等来构建表达式。

Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.

这篇关于在JPA 2中,使用CriteriaQuery,如何计算结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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