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.
Use ParameterExpression. Note: Untested.
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<MyEntity> from = cq.from(MyEntity.class);
cq.select(cb.count(from));
ParameterExpression<Integer> p = cb.parameter(Integer.class);
q.where(cb.eq(from.get("age"), 45));
return entityManager.createQuery(cq).getSingleResult();