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

如何在Spring Boot的GetMapping中仅返回数据库单列name的值?

实现仅返回name单列的API接口

有三种常用方式可以实现需求,按推荐优先级排序:

方法一:直接在Repository中查询name字段(推荐)

这种方式会让JPA生成只查询name列的SQL,性能最优。

  1. 修改PURRepository,新增查询name的方法:
@Repository
public interface PURRepository extends JpaRepository<PUR, Long> {
    ArrayList<PUR> findAllByDevice(String device);
    Optional<PUR> findByDevice(String device);
    // 新增方法:根据device查询所有name值
    List<String> findNameByDevice(String device);
}
  1. 修改Controller方法,返回字符串列表:
@RestController
public class PURController {
    @Autowired
    private PURRepository purRepository;

    @CrossOrigin()
    @GetMapping("/purs/getname/{device}")
    public ResponseEntity<List<String>> getPurName(@PathVariable(value = "device") String device){
         List<String> names = purRepository.findNameByDevice(device);
        return ResponseEntity.ok().body(names);
    }
}

方法二:在Controller中转换已查询的实体列表

如果不想修改Repository,可以在内存中提取name字段,适合数据量较小的场景:

修改Controller方法,使用Stream API转换列表:

@RestController
public class PURController {
    @Autowired
    private PURRepository purRepository;

    @CrossOrigin()
    @GetMapping("/purs/getname/{device}")
    public ResponseEntity<List<String>> getPurName(@PathVariable(value = "device") String device){
         ArrayList<PUR> purList = purRepository.findAllByDevice(device);
         // 提取所有name字段
         List<String> names = purList.stream()
                                     .map(PUR::getName)
                                     .collect(Collectors.toList());
        return ResponseEntity.ok().body(names);
    }
}

注意:这种方式会查询实体的所有字段,再在内存中过滤,数据量大时性能不如方法一。

方法三:使用投影接口(适合需扩展返回字段的场景)

如果后续可能需要返回更多字段但不想返回完整实体,可以用投影接口:

  1. 创建投影接口:
import com.fasterxml.jackson.annotation.JsonValue;

public interface PurNameProjection {
    // @JsonValue让Jackson直接序列化返回name值,而非嵌套对象
    @JsonValue
    String getName();
}
  1. 修改Repository方法返回投影列表:
@Repository
public interface PURRepository extends JpaRepository<PUR, Long> {
    ArrayList<PUR> findAllByDevice(String device);
    Optional<PUR> findByDevice(String device);
    // 返回投影接口列表
    List<PurNameProjection> findByDevice(String device);
}
  1. 修改Controller方法:
@RestController
public class PURController {
    @Autowired
    private PURRepository purRepository;

    @CrossOrigin()
    @GetMapping("/purs/getname/{device}")
    public ResponseEntity<List<PurNameProjection>> getPurName(@PathVariable(value = "device") String device){
         List<PurNameProjection> names = purRepository.findByDevice(device);
        return ResponseEntity.ok().body(names);
    }
}

这种方式也只会查询name列,且后续可以在投影接口中添加其他getter方法来扩展返回字段。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:03:36