0

I have an arbitrary JPA criteria query. I would like to know how many results that query would produce without transferring all the results from the database.

So basically I would like to create a query

select count(*) from (<the arbitrary criteria query>)

The problem is that either I don't know how to create a SubQuery from the original CriteriaQuery when implementing this like:

CriteriaQuery<Integer> countQuery = criteriaBuilder.createQuery(Integer.class);
criteriaBuilder.count(criteriaQuery);

Or I'm missing another way to implement it.

How can I do this using JPA?

Edit:
This is not a duplicate of How do I count the number of rows returned by subquery?, because I already have a CriteriaQuery instance at hand, that I would like to incorporate into a new query or modify. The other question is about crafting a query from scratch. The point this question is about is how to use the CriteriaQuery instance I already have at hand.

SpaceTrucker
  • 13,377
  • 6
  • 60
  • 99
  • Possible duplicate of [How do I count the number of rows returned by subquery?](https://stackoverflow.com/questions/5423937/how-do-i-count-the-number-of-rows-returned-by-subquery) – Peter Šály Mar 16 '19 at 23:28

1 Answers1

0

It is not possible to use a CriteriaQuery as a Subquery.

One way to count the number of rows is to use the getResultList() method.

return criteriaBuilder.createQuery(criteriaQuery).getResultList().size()

In my opinion, this is not an optimal solution, but works when you expect small result list. Otherwise you need to rewrite your existing CriteriaQuery as explained here.

Marcel Goldammer
  • 72
  • 1
  • 1
  • 6