srk
srk

Reputation: 5126

How to count the results from a Custom Entity using JPA CriteriaQuery

I am using JPA2.1 criteria API where in I have created a result object using criteria builder construct.

Consider the below sample piece of code.

CriteriaBuilder cb;//Assume cb is obtained here 
CriteriaQuery<Report> cq = cb.createQuery(Report.class);// custom selective Class
Root<Student> root = cq.from(Student.class);
Join<Student, XTable> join1 = root.join("xtable", JoinType.INNER);
Join<Student, YTable> join1 = root.join("ytable", JoinType.INNER); 

Below is the main line where I would select.

cq.select(cb.construct(Report.class,
      root.get("name"), join1.get("address_type"), join2.get("country")));

Now, I would like to do a count on this construct Report.

I tried count like this.

cq.select(cb.count(cb.construct(......)));
// Failed because count accepts Expression and I tried assigning the cb.construct to Expression which is not working.

How to get the count?

Upvotes: 1

Views: 3043

Answers (1)

seba.wagner
seba.wagner

Reputation: 3860

I think it would look something like this:

Your code:

CriteriaBuilder cb;//Assume cb is obtained here 
CriteriaQuery<Report> cq = cb.createQuery(Report.class);// custom selective Class
Root<Student> root = cq.from(Student.class);
Join<Student, XTable> join1 = root.join("xtable", JoinType.INNER);
Join<Student, YTable> join1 = root.join("ytable", JoinType.INNER); 
countItemsByCriteria(entityManagerReference, cq, cb);


private <T> Long countItemsByCriteria(EntityManager em, CriteriaQuery<T> cqEntity, CriteriaBuilder cb) {
    CriteriaBuilder builder = cb;
    CriteriaQuery<Long> cqCount = builder.createQuery(Long.class);
    Root<?> entityRoot = cqCount.from(cqEntity.getResultType());
    cqCount.select(builder.count(entityRoot));
    cqCount.where(cqEntity.getRestriction());
    return em.createQuery(cqCount).getSingleResult();
}

As also described in this post: JPA + Hibernate count(*) using CriteriaBuilder - with generatedAlias

Upvotes: 4

Related Questions