Search code examples
jpajpa-2.0jpqlcriteria-api

How do I count the number of rows returned by subquery?


I want to do something like this:

select count(*) from (select ...)

(As it would be in SQL), but in JPA.

Any ideas on how I would do it?


Solution

  • This should do the trick (If you want to use JPA criteria API):

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();  
    CriteriaQuery<Long> query = cb.createQuery(Long.class);
    
    Root<Entity> root = query.from(Entity.class);
    
    //Selecting the count
    query.select(cb.count(root));
    
    //Create your search criteria
    Criteria criteria = ...
    
    //Adding search criteria   
    query.where(criteria);
    
    Long count = getEntityManager().createQuery(query).getSingleResult();
    

    On the other hand, if you want to use JP-QL, the following code should do the trick:

    //Add the where condition to the end of the query
    Query query = getEntityManager().createQuery("select count(*) from Entity entity where...")
    Long count = query.getSingleResult();