0

I have a query generated by hibernate criteria api which takes a pretty much time to execute:

select count (entity.id) 
from table 
where field1 in ('...') and field2 in ('...') and ...

I've replaced entity.id with '*':

select count (*) 
from table 
where field1 in ('...') and field2 in ('...') and ...

And for now it works pretty well for some reasons, but I can't generate this query by criteria api. I'am creating Root like this:

Root<MyEntity> root cq.from(MyEntity.class);

Is there any ways to generate sql query with select count(*) not with count(id)?

fonzy
  • 53
  • 1
  • 8
  • Does this answer your question? [JPA 2.0: count for arbitrary CriteriaQuery?](https://stackoverflow.com/questions/3997587/jpa-2-0-count-for-arbitrary-criteriaquery) – Petr Aleksandrov Dec 10 '20 at 16:44

1 Answers1

1

Use count(1) which is equivalent by doing criteriaBuilder.count(criteriaBuilder.literal(1))

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
  • hi, I had this problem for a while, criteriaBuilder.literal(1) not working in older hibernate, sum(1) works like count(*), I test criteriaBuilder.sum(criteriaBuilder.literal(1)) and my problem solved – fatemeakbari Aug 29 '22 at 04:20