AI Hints
Home›Spring Boot Tutorial›PATCH, Filtering with Query Parameters and Pagination in the API
Spring Boot · Lesson 85 of 120

PATCH

Change just one field.

⏱ 2 min read▶ Video at 1:53:47🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

PUT replaces the whole book. But often a client wants to change just one field, like the price. That's what PATCH is for.

  • PUT replaces everything
  • Change just one field
  • PATCH

PUT and PATCH

With PUT, the client sends every field, and missing fields would be wiped. With PATCH, the client sends only the fields that change. Everything else stays as it was.

PUT

  • Send the whole bookReplaces everythingMissing = wiped

PATCH

  • Send only changesUpdates some fieldsMissing = untouched

Applying only what was sent

Patch book uses wrapper types, like capital D Double, so a missing value is null. The service changes only the fields that are not null. Dirty checking saves the result, as before.

PatchBook.java · BookService.javajava
public record PatchBook(String title, String author, @Positive Double price) {}

    public BookResponse patch(long id, PatchBook req) {
        Book book = books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
        if (req.title() != null) book.setTitle(req.title());
        if (req.author() != null) book.setAuthor(req.author());
        if (req.price() != null) book.setPrice(req.price());
        return BookResponse.from(book);
    }

PATCH /books/{id}

At Patch Mapping handles PATCH requests. Run it. First we change only the price. Then only the title, and the new price is kept. And a negative price is still rejected, because the rules still apply.

BookController.javajava
@RestController
public class BookController {

    private final BookService service;

    public BookController(BookService service) { this.service = service; }

    @PatchMapping("/books/{id}")
    public BookResponse patch(@PathVariable long id, @Valid @RequestBody PatchBook req) {
        return service.patch(id, req);
    }
}
Output
$ curl -X PATCH --json '{"price":7.49}' localhost:8080/books/1
{"id":1,"title":"Dune","author":"Frank Herbert","price":7.49}
$ curl -X PATCH --json '{"title":"Dune (Deluxe)"}' localhost:8080/books/1
{"id":1,"title":"Dune (Deluxe)","author":"Frank Herbert","price":7.49}
$ curl -i -X PATCH --json '{"price":-1}' localhost:8080/books/1 | head -1
HTTP/1.1 400
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> {}
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=true
Also uses BookService.java
@Service
@Transactional
public class BookService {

    private final BookRepository books;

    public BookService(BookRepository books) { this.books = books; }

    public BookResponse patch(long id, PatchBook req) {
        Book book = books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
        if (req.title() != null) book.setTitle(req.title());
        if (req.author() != null) book.setAuthor(req.author());
        if (req.price() != null) book.setPrice(req.price());
        return BookResponse.from(book);
    }
}
Also uses PatchBook.java
public record PatchBook(String title, String author, @Positive Double price) {}
Also uses _curl.sh
curl -X PATCH --json '{"price":7.49}' localhost:8080/books/1
curl -X PATCH --json '{"title":"Dune (Deluxe)"}' localhost:8080/books/1
curl -i -X PATCH --json '{"price":-1}' localhost:8080/books/1 | head -1

Summary

PATCH changes only the fields sent. Use nullable fields in the request, and apply the ones that aren't null. Next, filtering with query parameters.

Key takeaways
  • @PatchMapping
  • Nullable fields
  • Apply what was sent
Next up: Filtering with Query Parameters — optional filters