I am using Java8 with Hibernate5 and JPA2. I would like to count the number of rows in a result set. I have the following code that works, however, I would like to know if there's a more efficient way of doing it? I think the code below first queries the entire result set and the counts the rows.
final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
CriteriaQuery<Rating> criteria = criteriaBuilder.createQuery(Rating.class);
Root<Rating> root = criteria.from(Rating.class);
ParameterExpression<Job> param = criteriaBuilder.parameter(Job.class);
TypedQuery<Rating> queryRating = entityManager.createQuery(criteria);
queryRating.setParameter(param, job);
int results = queryRating.getResultList().size();
Is there a way of rather making the SQL do a count(*)
?
UPDATE
Thanks to @chsdk below, I have a revised version of code:
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(Rating.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
Question
How do I set the where
clause with the Job
parameter?
More info:
+--------+ +------------+ +-----+
| rating | | rating_job | | job |
+--------+ +------------+ +-----+
| ID | | RAT_ID | | ID |
| | | JOB_ID | | |
+--------+ +------------+ +-----+
Rating.java
@ManyToOne(fetch=FetchType.EAGER)
@JoinTable
(
name="rating_job",
joinColumns={ @JoinColumn(name="RAT_ID", referencedColumnName="ID") },
inverseJoinColumns={ @JoinColumn(name="JOB_ID", referencedColumnName="ID") }
)
private Job job;
UPDATE
Thanks to @chsdk, here is my version that works:
final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class);
Root<Rating> root = criteria.from(Rating.class);
ParameterExpression<Job> param = criteriaBuilder.parameter(Job.class);
criteria.select(criteriaBuilder.count(root)).where(criteriaBuilder.equal(root.get("job"), param));
TypedQuery<Long> queryRating = entityManager.createQuery(criteria);
queryRating.setParameter(param, job);
Long results = queryRating.getSingleResult();
return results;