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

Spring Boot REST Controller如何获取多个ID?

在Spring Boot中实现支持多ID批量查询的端点

1. 直接用@RequestParam接收参数

这是最直接的实现方式,通过@RequestParam指定参数名id[in],直接绑定到集合类型(比如List<Integer>)即可。

示例Controller代码:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class InvoiceController {

    // 原有单ID查询端点(按需保留)
    @GetMapping("/api/invoice")
    public Object getSingleInvoice(@RequestParam(required = false) Integer id) {
        // 原有单ID查询逻辑
        return null;
    }

    // 新增多ID查询端点
    @GetMapping("/api/invoice")
    public Object getBatchInvoices(@RequestParam("id[in]") List<Integer> ids) {
        // 根据传入的ID列表批量查询发票的业务逻辑
        // 比如调用Service层查询数据库
        return "查询ID列表:" + ids + "对应的发票数据";
    }
}

注意:如果新旧端点路径相同,要调整参数的required属性避免匹配冲突。比如原有端点的id设为required=false,当请求携带id[in]时会自动匹配到多ID查询方法。

2. 封装查询参数对象(更易扩展)

如果后续需要添加更多查询条件,可以封装一个查询DTO,让参数绑定更优雅:

先定义查询参数类:

import java.util.List;

public class InvoiceQueryParam {
    private List<Integer> id;

    // Getter和Setter方法
    public List<Integer> getId() {
        return id;
    }

    public void setId(List<Integer> id) {
        this.id = id;
    }
}

然后在Controller中使用:

@GetMapping("/api/invoice")
public Object getBatchInvoices(InvoiceQueryParam queryParam) {
    List<Integer> ids = queryParam.getId();
    // 批量查询逻辑
    return "查询ID列表:" + ids + "对应的发票数据";
}

Spring会自动将请求参数id[in]绑定到InvoiceQueryParam的id属性,原生支持这种集合类型的参数命名规则。

3. 结合Spring Data JPA实现数据库查询

如果需要从数据库批量查询发票,可在Repository层定义支持In查询的方法:

Repository接口:

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface InvoiceRepository extends JpaRepository<Invoice, Integer> {
    List<Invoice> findByIdIn(List<Integer> ids);
}

Service层调用:

import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class InvoiceService {
    private final InvoiceRepository invoiceRepository;

    public InvoiceService(InvoiceRepository invoiceRepository) {
        this.invoiceRepository = invoiceRepository;
    }

    public List<Invoice> getInvoicesByIds(List<Integer> ids) {
        return invoiceRepository.findByIdIn(ids);
    }
}

最后在Controller中注入Service并使用:

@GetMapping("/api/invoice")
public List<Invoice> getBatchInvoices(@RequestParam("id[in]") List<Integer> ids) {
    return invoiceService.getInvoicesByIds(ids);
}

关键注意事项

  • Spring默认会自动将逗号分隔的参数值转换为集合,无需额外配置;如果需要其他分隔符,可以自定义Converter或者手动拆分字符串。
  • 确保同路径下的Controller方法参数匹配逻辑清晰,避免请求匹配冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:15:34