I'm writing a module that provides data for a UI table, where a user can pass a JPA Criteria query. Fetching the data is fine. However I couldn't find a solution to count the rows from the query to specify the "length" for the table.
What I want to do is to pass the query as a subquery in the FROM part of a new query, but I don't know if this even possible with Criteria.
The resulting SQL should be something like this:
SELECT count(1) FROM <user specified query as subquery>
All the examples that I found said I should recreate the query with the same root, the same joins...etc. And change the selection to contain the count, but thats much more complicated than this and also, if I do that I have to think of stuff like: what if the original query contained a group by clause, how do I copy that to a new query without getting multiple rows in the result.
I'd tried to do this:
CriteriaQuery countingQuery = criteriaBuilder.createQuery(Long.class);
Root from = countingQuery.from(userSpecifiedQuery.subquery(entityClass));
countingQuery.select(criteriaBuilder.count(criteriaBuilder.literal(1L)));
But there is no from
method that accepts Subquery
as a parameter.
The Subquery
class has the correlate
method which would create a Root
from the Subquery
, which could be used instead of the countingQuery.from()
, but I couldn't figure out what root to pass to the correlate
method.
The java-doc sais:
/**
* Create a subquery root correlated to a root of the
* enclosing query.
* @param parentRoot a root of the containing query
* @return subquery root
*/
It's confuses me more. Isn't the "enclosing" query's root in my case would be the root created by this method? (Or maybe this method does something completely different what I thought? )