首页 > 解决方案 > 如何遍历 JPA 响应并从中获取值

问题描述

存储库中的代码是

@Query("select divisionName, count(stundeName)FROM StudentDetails GROUP BY divisionName")
    public List<Object> getDivisionCount();

服务中的代码是

List <Object> countList= studentDetailsRepository.getDivisionCount();

现在我想遍历 countList 和 categories 然后进入不同的类别,我试过这个

for(int i=0;i< countList.size();i++ )
    System.out.println(countList.get(i).getClass().getDeclaredField('count'));

它不起作用并给出错误

标签: javaspring-bootjpa

解决方案


最好在 JPA 响应上使用投影。一种选择是使用基于界面的投影。在您的情况下,查询可能如下所示:

@Query(value = "SELECT s.divisionName AS divisionName, count(s.stundeName) AS stundeName FROM StudentDetails AS s GROUP BY s.divisionName")
public List<StudentDetails> getDivisionCount();

然后你需要创建一个这样的接口:

public interface StudentDetails{
    String getDivisionName();
    String getStundeName();
}

推荐阅读