Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 519
Harun ERGUL Avatar asked Jan 29 '15 10:01

Harun ERGUL


People also ask

What is countQuery JPA?

countQuery. Defines a special count query that shall be used for pagination queries to lookup the total number of elements for a page.

What does getSingleResult return?

getSingleResult. Execute a SELECT query that returns a single untyped result.


3 Answers

The best and simple way in jpa :

public interface YourEntityRepository extends JpaRepository<YourEntity, Serializable> {

Long countByAgeGreaterThan(Integer age);

}
like image 103
jdominus Avatar answered Oct 31 '22 14:10

jdominus


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.

like image 21
Buhake Sindi Avatar answered Oct 31 '22 14:10

Buhake Sindi


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();
like image 4
RichardK Avatar answered Oct 31 '22 12:10

RichardK