如何使用Spring Data JPA返回日期和该日期的记录计数?

时间:2019-02-21 07:25:33

标签: java hibernate spring-data-jpa

我想按日期返回事件计数。下面是我的代码

@Query(value = "select DATE(e.startTime) as day,count(distinct e.id) as eventCount from events e " +
            "where e.clientId=:clientId and e.startTime>=:firstDay and e.startTime<=:lastDay group by DATE(e.startTime)",nativeQuery = true)
    Map<Integer, Integer> getClientEventsCountByDay(@Param(value = "clientId") Integer clientId,
                                                    @Param(value = "firstDay") String firstDay,
                                                    @Param(value = "lastDay") String lastDay);

输入的值为clientId = 2510,firstDay = 2019-01-01,lastDay = 2019-01-31

此查询抛出错误

  

原因:   org.springframework.dao.IncorrectResultSizeDataAccessException:结果   返回多个元素;嵌套异常为   javax.persistence.NonUniqueResultException:返回的结果超过   一个元素

但是,直接在db上运行时,此查询工作正常。 enter image description here

1 个答案:

答案 0 :(得分:0)

尝试更改为此

List<Map<Integer, Integer>> getClientEventsCountByDay(@Param(value = "clientId") Integer clientId,
                                                @Param(value = "firstDay") String firstDay,
                                                @Param(value = "lastDay") String lastDay);