Hibernate JPA 2.0 CriteriaQuery, subset listing and counting at once
Posted
by Jeroen
on Stack Overflow
See other posts from Stack Overflow
or by Jeroen
Published on 2010-04-21T17:38:32Z
Indexed on
2010/04/21
17:43 UTC
Read the original article
Hit count: 639
Hello, I recently started using the new Hibernate (EntityManager) 3.5.1 with JPA 2.0, and I was wondering if it was possible to both retrieve a (sub-set) of entities and their count from a single CriteriaQuery instance.
My current implementation looks as follows:
class HibernateResult<T> extends AbstractResult<T> {
/**
* Construct a new {@link HibernateResult}.
* @param criteriaQuery the criteria query
* @param selector the selector that determines the entities to return
*/
HibernateResult(CriteriaQuery<T> criteriaQuery, Selector selector, EntityManager entityManager) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
// Count the entities
CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
Root<T> path = criteriaQuery.from(criteriaQuery.getResultType());
countQuery.select(builder.count(path));
final int count = entityManager.createQuery(countQuery).getSingleResult().intValue();
this.setCount(count);
// List the entities according to selector
TypedQuery<T> entityQuery = entityManager.createQuery(criteriaQuery);
entityQuery.setFirstResult(selector.getFirstResult());
entityQuery.setMaxResults(selector.getMaxRecords());
List<T> entities = entityQuery.getResultList();
this.setEntities(entities);
}
}
The thing is that I want to count all entities that match my criteria query, but the count method from CriteriaBuilder only seems to take Expression as argument. Is there any quick way of converting my criteria query to an expression?
© Stack Overflow or respective owner