Skip to content
Advertisement

How to count number of rows using JPA?

I try to count number of rows using JPA.I want to use where clause however I can’t.

CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where();  //how to write where clause 
return entityManager.createQuery(cq).getSingleResult();

How can I set where clause forexample where age=”45″. Thanks in advance.

Advertisement

Answer

Use ParameterExpression. Note: Untested.

CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
ParameterExpression<Integer> p = qb.parameter(Integer.class);
q.where(qb.eq(c.get("age"), 45));
return entityManager.createQuery(cq).getSingleResult();

Reference.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement