首页 > 解决方案 > 如何在标准 api 中选择 count(*)?

问题描述

我有一个由休眠条件 api 生成的查询,它需要很长时间才能执行:

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

我已将 entity.id 替换为“*”:

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

现在由于某些原因它工作得很好,但我无法通过标准 api 生成这个查询。我正在像这样创建 Root :

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

有什么方法可以使用 select count(*) 而不是 count(id) 生成 sql 查询?

标签: hibernatejpahibernate-criteriacriteria-api

解决方案


使用count(1)相当于做criteriaBuilder.count(criteriaBuilder.literal(1))


推荐阅读