java 27 lines · 6 steps

Binding collection query params in Spring

A Spring REST endpoint maps repeated and comma-separated query parameters into typed collections and folds them into a filter.

Explained by highlit
1@RestController
2@RequestMapping("/api/products")
3public class ProductSearchController {
4 
5 private final ProductQueryService productQueryService;
6 
7 public ProductSearchController(ProductQueryService productQueryService) {
8 this.productQueryService = productQueryService;
9 }
10 
11 @GetMapping
12 public List<ProductView> search(
13 @RequestParam(name = "tags", required = false) List<String> tags,
14 @RequestParam(name = "ids", defaultValue = "") Set<Long> ids,
15 @RequestParam(name = "status", required = false) EnumSet<ProductStatus> statuses) {
16 
17 ProductFilter filter = ProductFilter.builder()
18 .tags(tags == null ? List.of() : tags)
19 .ids(ids)
20 .statuses(statuses == null ? EnumSet.allOf(ProductStatus.class) : statuses)
21 .build();
22 
23 return productQueryService.findMatching(filter).stream()
24 .map(ProductView::from)
25 .toList();
26 }
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Spring can bind a query parameter straight into a List, Set, or EnumSet, converting each element to the target type automatically.
  2. 2Defaulting absent optional parameters at the controller boundary keeps downstream services free of null checks.
  3. 3Mapping entities to view objects before returning keeps the API contract decoupled from the persistence model.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Binding collection query params in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code