Spring Boot · Lesson 86 of 120
Filtering with Query Parameters
Optional filters.
Clients want to filter lists. Books by an author, under a price, or both, or neither. One endpoint should handle every combination.
- By author
- Under a price
- Any combination
One query, optional filters
This JPQL query has two optional conditions. If author is null, the first condition is always true. The same trick works for the maximum price. So one query handles every combination.
BookRepository.javajava
public interface BookRepository extends JpaRepository<Book, Long> {
@Query("""
SELECT b FROM Book b
WHERE (:author IS NULL OR b.author = :author)
AND (:maxPrice IS NULL OR b.price <= :maxPrice)
ORDER BY b.price""")
List<Book> search(@Param("author") String author, @Param("maxPrice") Double maxPrice);
}GET /books with filters
Both parameters are optional, so they're null when missing. The controller passes them straight to the query. With no filters at all, it returns every book. Run it. First, only Austen's books. Then everything up to eight fifty. And finally, Herbert's books, up to nine.
BookController.javajava
@RestController
public class BookController {
private final BookRepository books;
public BookController(BookRepository books) { this.books = books; }
@GetMapping("/books")
public List<BookResponse> list(@RequestParam(required = false) String author,
@RequestParam(required = false) Double maxPrice) {
return books.search(author, maxPrice).stream().map(BookResponse::from).toList();
}
}Output
$ curl "localhost:8080/books?author=Jane%20Austen"
[
{"id":7,"title":"Emma","author":"Jane Austen","price":6.99},
{"id":8,"title":"Persuasion","author":"Jane Austen","price":7.49}
]
$ curl "localhost:8080/books?maxPrice=8.5"
[
{"id":7,"title":"Emma","author":"Jane Austen","price":6.99},
{"id":8,"title":"Persuasion","author":"Jane Austen","price":7.49},
{"id":4,"title":"Children of Dune","author":"Frank Herbert","price":8.49}
]
$ curl "localhost:8080/books?author=Frank%20Herbert&maxPrice=9"
[{"id":4,"title":"Children of Dune","author":"Frank Herbert","price":8.49}]Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setTitle(String title) { this.title = title; }
public void setAuthor(String author) { this.author = author; }
public void setPrice(double price) { this.price = price; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
@Query("""
SELECT b FROM Book b
WHERE (:author IS NULL OR b.author = :author)
AND (:maxPrice IS NULL OR b.price <= :maxPrice)
ORDER BY b.price""")
List<Book> search(@Param("author") String author, @Param("maxPrice") Double maxPrice);
}Also uses CreateBook.java
public record CreateBook(
@NotBlank String title,
@NotBlank String author,
@Positive double price
) {}Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {
static BookResponse from(Book b) {
return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
}
}Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}Also uses GlobalErrors.java
@RestControllerAdvice
public class GlobalErrors {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail notFound(BookNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
}Also uses data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49),
('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
('Emma', 'Jane Austen', 6.99),
('Persuasion', 'Jane Austen', 7.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueAlso uses _curl.sh
curl "localhost:8080/books?author=Jane%20Austen"
curl "localhost:8080/books?maxPrice=8.5"
curl "localhost:8080/books?author=Frank%20Herbert&maxPrice=9"Summary
Optional request parameters, and an is null or condition, give one endpoint that handles any mix of filters. Next, pagination in the API.
Key takeaways- required = false
- IS NULL OR ...
- One flexible endpoint
Next up: Pagination in the API — ?page=0&size=20