Is there a way, to wrap a CriteriaQuery with a count query? My idea was that to create a function that create a count query from any given query.
For example in plane sql:
SELECT
item_type,
count(*) AS lol
FROM inventory_movements
WHERE movement_date_time BETWEEN '2017-05-08 12:00:00' AND '2017-05-08 13:00:00'
GROUP BY item_type
and i want to create something like this(i know in this specific query a count distinct would solve the problem, but i need a generic solution, i want to use it for paging in non jpa managed return type queries):
SELECT count(*)
FROM (
SELECT
item_type,
count(*) AS rand_
FROM inventory_movements
WHERE movement_date_time BETWEEN '2017-05-08 12:00:00' AND '2017-05-08 13:00:00'
GROUP BY item_type
) AS sub;
CriteriaQuery is not instance of Expression so it's cant be use in criteriaBuilder.count();
Then i thought i can cast it to a Subquery, since both CriteriaQuery and Subquery implements the same Interfaces, but Subquery also implements Expression.
But this was not work as i think. This is my current non working code right now:
public <T>TypedQuery<Long> getCountQuery(CriteriaQuery<T> origQuery) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> query = cb.createQuery(Long.class);
Subquery<T> subQuery = (Subquery<T>) origQuery;
query.select(cb.count(subQuery));
return entityManager.createQuery(query);
}
I get the following exception during run time:
java.lang.ClassCastException: org.hibernate.query.criteria.internal.CriteriaQueryImpl cannot be cast to javax.persistence.criteria.Subquery
Is this even possible in jpa/hibernate?