【问题标题】:Get SUM instead of COUNT without native Query在没有本机查询的情况下获取 SUM 而不是 COUNT
【发布时间】:2020-12-01 15:28:27
【问题描述】:

我正在使用带有 MySQL 数据库的 Spring Data JPA。我有以下数据库表:

id   points   user_id
1    35       1
2    40       1
3    25       1
4    2500     2

我想获得points 列的SUM(),但不是使用本机查询。

在存储库中,我可以使用方法来COUNT() 行。当我尝试 sum 而不是 count 时,我得到一个错误。

public interface MyRepository extends JpaRepository<MyEntity, Long> {
    
    public Long countPointsByUser(User user); // for user #1 returns 3
    public Long sumPointsByUser(User user); // throws an exception, but I want return of 100 for user #1 and 2500 for user #2

}

Spring Data JPA 是否可以在没有@Query 注释的接口中编写方法?

【问题讨论】:

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


【解决方案1】:

我有一个解决方案。在我的情况下,它适合。

我使用SUM(points) 创建一个视图,为视图创建一个实体,为新实体创建一个存储库,然后调用findAll()

感谢您的帮助。这解释了为什么在文档中找不到任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2020-03-13
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多