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.
countQuery. Defines a special count query that shall be used for pagination queries to lookup the total number of elements for a page.
getSingleResult. Execute a SELECT query that returns a single untyped result.
The best and simple way in jpa :
public interface YourEntityRepository extends JpaRepository<YourEntity, Serializable> {
Long countByAgeGreaterThan(Integer age);
}
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.
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("your table name");
EntityManager em = emf.createEntityManager();
// JPA Query Language is executed on your entities (Java Classess), not on your database tables;
Query query = em.createQuery("SELECT count(*) FROM your Classname WHERE ... etc");
long count = (long) query.getSingleResult();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With