在 JPA 2 中,使用 CriteriaQuery,如何计算结果
我对 JPA 2 相当陌生,它是 CriteriaBuilder / CriteriaQuery API:
我想计算 CriteriaQuery 的结果,而不实际检索它们。这可能吗,我没有找到任何这样的方法,唯一的方法就是这样做:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyEntity> cq = cb
.createQuery(MyEntityclass);
// initialize predicates here
return entityManager.createQuery(cq).getResultList().size();
这不可能是正确的方法......
有解决方案吗?
I am rather new to JPA 2 and it's CriteriaBuilder / CriteriaQuery API:
CriteriaQuery
in the Java EE 6 tutorial
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...
Is there a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
MyEntity
类型的查询将返回MyEntity
。您想要查询Long
。显然,您将希望使用示例中跳过的任何限制和分组等来构建您的表达式。
A query of type
MyEntity
is going to returnMyEntity
. You want a query for aLong
.Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.
我已经使用 cb.createQuery() (没有结果类型参数)解决了这个问题:
希望它有帮助:)
I've sorted this out using the cb.createQuery() (without the result type parameter):
Hope it helps :)
由于其他答案是正确的,但太简单了,因此为了完整起见,我将提供下面的代码片段,以在复杂 JPA Criteria 查询(具有多个联接、获取)上执行
SELECT COUNT
, 状况)。这个答案略有修改。
希望它可以节省某人的时间。
因为恕我直言,JPA Criteria API 不直观,也不太可读。
As others answers are correct, but too simple, so for completeness I'm presenting below code snippet to perform
SELECT COUNT
on a sophisticated JPA Criteria query (with multiple joins, fetches, conditions).It is slightly modified this answer.
Hope it saves somebody's time.
Because IMHO JPA Criteria API is not intuitive nor quite readable.
这有点棘手,具体取决于您使用的 JPA 2 实现,这个适用于 EclipseLink 2.4.1,但不适用于 Hibernate,这里是 EclipseLink 的通用 CriteriaQuery 计数:
前几天我从 EclipseLink 迁移到 Hibernate 并有将我的计数函数更改为以下内容,因此请随意使用,因为这是一个很难解决的问题,它可能不适用于您的情况,它自 Hibernate 4.x 以来一直在使用,请注意,我不尝试为了猜测哪个是根,而是从查询中传递它,这样问题就解决了,有太多模棱两可的极端情况无法尝试猜测:
It is a bit tricky, depending on the JPA 2 implementation you use, this one works for EclipseLink 2.4.1, but doesn't for Hibernate, here a generic CriteriaQuery count for EclipseLink:
The other day I migrated from EclipseLink to Hibernate and had to change my count function to the following, so feel free to use either as this is a hard problem to solve, it might not work for your case, it has been in use since Hibernate 4.x, notice that I don't try to guess which is the root, instead I pass it from the query so problem solved, too many ambiguous corner cases to try to guess:
您还可以使用投影:
You can also use Projections: