【问题标题】:How to distinct counting with Spring JPA Repository如何使用 Spring JPA Repository 区分计数
【发布时间】:2018-11-13 16:46:49
【问题描述】:

如何使用 Spring Data JPA 进行不同的计数?我不想使用 @Query 注释。等效的 sql 查询将是:

SELECT COUNT(DISTINCT rack) FROM store WHERE id = 10001;

我尝试编写以下查询,但它不起作用:

int countDistinctRackById();

【问题讨论】:

    标签: spring spring-boot spring-data-jpa spring-repositories


    【解决方案1】:

    这应该可行:

    Integer countDistinctRackById(Long id);
    

    【讨论】:

    • 我刚刚测试了这种方法,它不起作用(Spring Boot 2.2.2)。请提供更多信息
    • 您能提供更多信息吗?实体类、存储库方法等?
    • 当然。我的仓库从JpaRepository 扩展,实体类具有customerId 字段和decision 字段,我需要获取decision 代码是所需值之一的不同客户数量。我给了方法名countDistinctCustomerIdByDecisionIn,但是生成的SQL不是select count(distinct CUSTOMER_ID) ...而是select distinct count(distinct ID) ...
    • 不确定这是否有帮助,但这看起来像是 In 关键字的问题。我再次需要更多信息来帮助(方法的返回类型、实体的字段类型等)
    • 此方法实际上不会产生所选字段的不同计数。它返回主键的不同计数并完全忽略字段名称部分。
    【解决方案2】:

    我刚刚尝试过,现有的答案都不起作用。

    以下查询:

    Integer countDistinctRackById(String id);

    将呈现如下内容:

    select distinct count(table0_.rack) as col_0_0_ from table table0_ where table0_.id=?

    由于我目前坚持使用 Spring Boot 1.2.3,如果以后有任何更改,idk,但为了实现不同的计数,我必须定义一个自定义查询:

    @Query("Select count(distinct rack) from Table t where t.id = ?1")

    【讨论】:

      【解决方案3】:

      按照Spring Documentation试试这个:

      Integer countDistinctRackById(String id);
      

      将单词Rack替换为机架字段的实际名称

      【讨论】:

        猜你喜欢
        • 2017-11-23
        • 1970-01-01
        • 2018-01-09
        • 2019-11-03
        • 2017-08-22
        • 1970-01-01
        • 1970-01-01
        • 2014-08-31
        • 1970-01-01
        相关资源
        最近更新 更多