Spring Boot如何修改接口返回值类型,将数组转为带字段的对象格式
根因分析
当前接口返回无字段标识的数组,是因为原生SQL查询未指定结果映射规则,默认返回List<Object[]>类型,序列化后直接展示为嵌套数组,没有字段名映射。
解决方案(最简实现:接口投影)
- 步骤1:新建结果映射接口
// 放在dto或projection包下即可 public interface ResponsableProjection { // 方法名需和SQL查询的字段别名严格对应 Integer getNbrResponsable(); String getNom_personnel(); String getPrenom_personnel(); }
- 步骤2:修改Repository层代码
@Query(value ="SELECT count(pe.personnel_id) as nbrResponsable, pe.prenom_personnel, pe.nom_personnel " + " FROM personnel pe " + "join action_securisation ac on pe.personnel_id = ac.responsable_action_securisation_id " + "group by pe.prenom_personnel,pe.nom_personnel " , nativeQuery = true) // 替换原有无泛型的List为带投影泛型的返回类型 List<ResponsableProjection> ResponsableActionCorrective();
- 步骤3:修改Service层返回类型
public List<ResponsableProjection> ResponsableActionCorrectiveByPeriod() { return listeActionCorrectiveRepository.ResponsableActionCorrective(); }
- 步骤4:修改Controller层返回类型
@GetMapping("/responsableActionCorrectiveByPeriod") public List<ResponsableProjection> ResponsableActionCorrectiveByPeriod() { return listeActionCorrectiveService.ResponsableActionCorrectiveByPeriod(); }
备用方案(无需新建类,临时使用)
如果不需要做参数校验等后续处理,可直接将三层的返回类型统一改为List<Map<String, Object>>,无需新增接口,Spring会自动将查询结果的字段别名作为Map的key返回,也能得到预期的JSON格式。
内容的提问来源于stack exchange,提问作者ameur
相关产品推荐
相关产品推荐

