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

后端 未结 2 414
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 07:37

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 d

2条回答
  •  有刺的猬
    2020-12-15 07:59

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

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();  
    CriteriaQuery query = cb.createQuery(Long.class);
    
    Root 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();
    

提交回复
热议问题