【发布时间】:2018-06-05 16:00:00
【问题描述】:
今天我使用该代码计算我的数据库中的选择
total = protocoloRepository.count(
Specifications.where(ProtocoloSpecification.withNumero(filtro.getNumero()))
.and(ProtocoloSpecification.withTipo(filtro.getTipoProtocolo()))
.and(ProtocoloSpecification.withAndamento(filtro.getAndamento()))
.and(ProtocoloSpecification.withNatureza(filtro.getNatureza()))
.and(ProtocoloSpecification.withCliente(filtro.getCliente()))
.and(ProtocoloSpecification.withDataBetween(filtro.getCampoData(), filtro.getDtInicial(), filtro.getDtFinal()))
);
return total.intValue();
但是这段代码会生成这个sql:
Hibernate:
select
count(protocolo0_.id) as col_0_0_
from
protocolo protocolo0_
where
(
protocolo0_.tipo_protocolo_id in (
? , ? , ? , ? , ? , ?
)
)
and (
protocolo0_.data_protocolo between ? and ?
)
那么我可以将那个 count(protocolo0_.id) 更改为 count(*),这个简单的更改在我的 sql 中需要 8 秒
【问题讨论】:
-
您对
id列有非空约束吗?你用的是什么数据库?让数据库意识到语句等同于更改 SQL 语句可能要容易得多。当然,您总是可以直接使用 SQL 语句。 -
我使用 postgresql 并且没有任何 null 它是我的主键(postgresql 中的序列是一个自动增量字段)
标签: hibernate spring-boot jpa spring-data-jpa