Search code examples
javahibernatejpacriteria

Jpa criteria count


I have new problem. I created some code, which generate Predicate, from client request. This is initializing part:

 criteriaBuilder = entityManager.getCriteriaBuilder();
 criteriaQuery = criteriaBuilder.createQuery(classEntity);
 root = criteriaQuery.from(classEntity);

When i want get list Entities it work great:

criteriaQuery.select(root).where(predicate);
entityManager.createQuery(criteriaQuery).getResultList();

But when i want to get count entities:

CriteriaQuery<Long> cq = criteriaBuilder.createQuery(Long.class);
cq.select(criteriaBuilder.count(root)).where(predicate);
System.err.println("eee : " +entityManager.createQuery(cq).getSingleResult());

it fall with exception

java.lang.IllegalArgumentException: Error occurred validating the Criteria Caused by: java.lang.IllegalStateException: No criteria query roots were specified

Probably i should said, that root generate dynamically joins:

private Path parseField(String field) {
    Path path = null;

    if (field.contains(".")) {

        String [] split = field.split("\\.");
        Join join = root.join(split[0],JoinType.INNER);

        for (int i =1; i < split.length-1; i++) {
            join = join.join(split[i],JoinType.INNER);
        }

        path = join.get(split[split.length-1]);

    } else {
        path = root.get(field);
    }
    return path;
}

if i replace

cq.select(criteriaBuilder.count(root)).where(previousPredicate);

on

cq.select(criteriaBuilder.count(cq.from(classEntity))).where(previousPredicate);

i will fail with exception

 org.hibernate.hql.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.(someFieldName)' 

Solution

  • It all works fine for me:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> q = cb.createQuery(Long.class);
    Root<A> r = q.from(A.class);
    MapJoin<A, String, String> m = r.joinMap("metadata");
    q.select(cb.count(r)).where(cb.equal(m.key(), "A"));
    Long rs = em.createQuery(q).getSingleResult();
    

    So, it's hard to see what your doing wrong without a MCVE.