4 回答
TA贡献1条经验 获得超1个赞
/* * @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();
TA贡献1797条经验 获得超6个赞
此SQL查询返回List <Object []>将。
您可以这样操作:
@RestController
@RequestMapping("/survey")
public class SurveyController {
@Autowired
private SurveyRepository surveyRepository;
@RequestMapping(value = "/find", method = RequestMethod.GET)
public Map<Long,String> findSurvey(){
List<Object[]> result = surveyRepository.findSurveyCount();
Map<Long,String> map = null;
if(result != null && !result.isEmpty()){
map = new HashMap<Long,String>();
for (Object[] object : result) {
map.put(((Long)object[0]),object[1]);
}
}
return map;
}
}
TA贡献1898条经验 获得超8个赞
使用接口,您可以获得更简单的代码。无需创建和手动调用构造函数
第1步:使用必填字段声明界面:
public interface SurveyAnswerStatistics {
String getAnswer();
Long getCnt();
}
步骤2:在接口中选择与getter名称相同的列,并从存储库方法返回intefrace:
public interface SurveyRepository extends CrudRepository<Survey, Long> {
@Query("select v.answer as answer, count(v) as cnt " +
"from Survey v " +
"group by v.answer")
List<SurveyAnswerStatistics> findSurveyCount();
}
添加回答
举报