You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Spring Boot如何返回姓名数组形式的查询结果?

解决Spring Boot接口返回姓名数组的问题

有两种常见方式可以实现接口返回[karthi,keyan,ram]格式的姓名数组:

方式一:直接从数据库查询姓名列表

这种方式更高效,仅查询所需的name字段,避免多余数据传输:

  1. 修改Repository方法
    调整@Query的返回类型为List<String>,同时排除MongoDB默认返回的_id字段:
@Query(value = "{'age':{$gte:?0}}", fields = "{'name':1, '_id':0}")
List<String> abc(String age);
  1. 更新Service层方法
    将返回类型同步改为List<String>:
public List<String> findByAge(String age){
    return studentRepository.abc(age);
}
  1. 调整Controller接口
    把接口的返回类型修改为List<String>:
@GetMapping(value = "info/{age}")
public List<String> findByAge(@PathVariable(value = "age") String age) {
    return studentService.findByAge(age);
}

方式二:在Service层转换对象列表

如果不想改动Repository的返回类型,可以在Service层通过流操作提取姓名:

public List<String> findByAge(String age){
    return studentRepository.abc(age)
            .stream()
            .map(Student::getName)
            .collect(Collectors.toList());
}

此时Repository仍返回List<Student>,Controller的返回类型改为List<String>即可。

内容的提问来源于stack exchange,提问作者Karthikeyan I

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:50:20