如何从Spring Data JPA GROUP BY查询返回自定义对象

我正在使用Spring Data JPA开发Spring Boot应用程序。我正在使用自定义JPQL查询来按某个字段分组并获取计数。以下是我的存储库方法。


@Query(value = "select count(v) as cnt, v.answer from Survey v group by v.answer")

public List<?> findSurveyCount();

它正在工作,结果如下:


[

  [1, "a1"],

  [2, "a2"]

]

我想得到这样的东西:


[

  { "cnt":1, "answer":"a1" },

  { "cnt":2, "answer":"a2" }

]

我该如何实现?


达令说
浏览 8165回答 4
4回答

慕娘1492219

/* * @Query的sql使用原生sql语句 * findSurveyCount()的返回值使用Map<String,Object> */ @Query(value = "select count(v) as cnt, v.answer from Survey v group by v.answer",         nativeQuery=true) public List<Map<String,Object>> findSurveyCount();

互换的青春

此SQL查询返回List <Object []>将。您可以这样操作:&nbsp;@RestController&nbsp;@RequestMapping("/survey")&nbsp;public class SurveyController {&nbsp; &nbsp;@Autowired&nbsp; &nbsp;private SurveyRepository surveyRepository;&nbsp; &nbsp; &nbsp;@RequestMapping(value = "/find", method =&nbsp; RequestMethod.GET)&nbsp; &nbsp; &nbsp;public Map<Long,String> findSurvey(){&nbsp; &nbsp; &nbsp; &nbsp;List<Object[]> result = surveyRepository.findSurveyCount();&nbsp; &nbsp; &nbsp; &nbsp;Map<Long,String> map = null;&nbsp; &nbsp; &nbsp; &nbsp;if(result != null && !result.isEmpty()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map = new HashMap<Long,String>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (Object[] object : result) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put(((Long)object[0]),object[1]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return map;&nbsp; &nbsp; &nbsp;}&nbsp;}

汪汪一只猫

使用接口,您可以获得更简单的代码。无需创建和手动调用构造函数第1步:使用必填字段声明界面:public interface SurveyAnswerStatistics {&nbsp; String getAnswer();&nbsp; Long getCnt();}步骤2:在接口中选择与getter名称相同的列,并从存储库方法返回intefrace:public interface SurveyRepository extends CrudRepository<Survey, Long> {&nbsp; &nbsp; @Query("select v.answer as answer, count(v) as cnt " +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"from Survey v " +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"group by v.answer")&nbsp; &nbsp; List<SurveyAnswerStatistics> findSurveyCount();}
打开App,查看更多内容
随时随地看视频慕课网APP