Search code examples
hibernatejpahibernate-criteriacriteria-api

How to select count(*) in criteria api?


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)?


Solution

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