In JPA 2, using a CriteriaQuery, how to count results

前端 未结 7 1162
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 19:28

I am rather new to JPA 2 and it\'s CriteriaBuilder / CriteriaQuery API:

CriteriaQuery javadoc

CriteriaQuery in the Java EE 6 tutorial

I would like to

7条回答
  •  无人及你
    2020-11-28 19:52

    A query of type MyEntity is going to return MyEntity. You want a query for a Long.

    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery cq = qb.createQuery(Long.class);
    cq.select(qb.count(cq.from(MyEntity.class)));
    cq.where(/*your stuff*/);
    return entityManager.createQuery(cq).getSingleResult();
    

    Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.

提交回复
热议问题