使用JpaRepository查询

时间:2016-07-20 03:02:36

标签: java mysql spring spring-boot spring-data-jpa

我有一个名为Submission的类和另一个存储库的SubmissionDAO。提交类有许多字段,如id,author,title,......

我想要做的是搜索数据库并获取数据库中每个作者值的(计数,作者)对的列表。

我提出了一个问题

@Query(value = "select author, count(*) from submissions GROUP BY author order by count(author) desc", nativeQuery = true)
List<Submission> findByAuthorOccurance();

显然,这不起作用,因为它无法将计数值放在Submission对象中。 我的问题是如何将这对价值回馈给我的控制器?

我试过搜索但没有出现。

1 个答案:

答案 0 :(得分:0)

如果有人因为某种原因将来这里,我想出了我的问题。

当您指定要从查询中获取的数据点范围(即作者和计数)时,它会将值分组到对象数组(Object [])中,并将它们放在正常的List中。

所以我的代码最终是这样的:

@Query(value = "select author, count(*) from submissions GROUP BY author order by count(author) desc", nativeQuery = true)
List<Object[]> findByAuthorOccurance();

查询和

   List<Object[]> map =submissionRepository.findByAuthorOccurance();
    for(Object[] objs : map){
        System.out.println((String)objs[0]+" : "+(BigInteger)objs[1]);
    }

获取数据。