【问题标题】:Change hibernate column count with spring boot使用弹簧靴更改休眠列数
【发布时间】: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


【解决方案1】:

从技术上讲,这里使用的上下文没有区别。

换句话说,COUNT(identifier-column) 返回指定列不为空的行数。对于标识符列,这始终是正确的,因此在语义上与使用 COUNT(*)COUNT(1) 相同。

在这种情况下更重要的是,COUNT(identifier-column) 通常可以比使用COUNT(*)COUNT(1) 执行得更好并返回更快的结果,因为始终会查询主键的 b 树索引 where-as the其他变体可能会更慢,因为可能会根据您的数据库平台进行全表扫描。

【讨论】:

  • 但如果我将 count(id) 更改为 count(*),我的 sql 运行速度会快 8 秒
  • 我相信这可能与其他事情有关,而不是 id*。我建议你运行一个解释计划,看看有什么区别,然后根据它进行调整,而不是推测。
猜你喜欢
  • 2016-07-09
  • 2016-11-04
  • 2020-03-13
  • 1970-01-01
  • 2019-05-03
  • 2017-12-22
  • 1970-01-01
  • 2011-08-09
  • 2012-01-22
相关资源
最近更新 更多