Update Requests
PUT through the layers.
Updating is a little special with JPA. We load the entity, change it, and that's it. We don't even need to call save.
- Load it
- Change it
- No save needed
The service update
Find by id, or else throw, loads the book, or throws our not found exception. Then we copy each new value into the entity. There's no call to save. Inside a transaction, JPA notices the changes, and writes them, when the method ends. This is called dirty checking.
@Service
@Transactional
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) { this.books = books; }
public BookResponse update(long id, UpdateBook req) {
Book book = books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
book.setTitle(req.title());
book.setAuthor(req.author());
book.setPrice(req.price());
return BookResponse.from(book);
}
}PUT /books/{id}
The controller validates the update request, and passes it to the service. Run it. Dune now costs seven ninety nine. And book ninety nine gets a four oh four problem detail, from our global handler.
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService service;
public BookController(BookService service) { this.service = service; }
@PutMapping("/{id}")
public BookResponse update(@PathVariable long id, @Valid @RequestBody UpdateBook req) {
return service.update(id, req);
}
}$ curl -X PUT --json '{"title":"Dune","author":"Frank Herbert","price":7.99}'
localhost:8080/books/1
{"id":1,"title":"Dune","author":"Frank Herbert","price":7.99}
$ curl -X PUT --json '{"title":"X","author":"Y","price":1}' localhost:8080/books/99
{"title":"Not Found","status":404,"detail":"Book 99 was not found"}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=trueAlso uses BookService.java
@Service
@Transactional
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) { this.books = books; }
public BookResponse update(long id, UpdateBook req) {
Book book = books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
book.setTitle(req.title());
book.setAuthor(req.author());
book.setPrice(req.price());
return BookResponse.from(book);
}
}Also uses UpdateBook.java
public record UpdateBook(
@NotBlank String title,
@NotBlank String author,
@Positive double price
) {}Also uses _curl.sh
curl -X PUT --json '{"title":"Dune","author":"Frank Herbert","price":7.99}' localhost:8080/books/1
curl -X PUT --json '{"title":"X","author":"Y","price":1}' localhost:8080/books/99Dirty checking
Entities loaded inside a transaction are watched by JPA. When the transaction commits, JPA compares them with how they were loaded. Any changed fields become an update statement, automatically.
| key | value |
|---|---|
| Loaded in a transaction | watched by JPA |
| You change fields | setPrice(...) |
| At commit | JPA compares |
| Result | UPDATE, automatically |
Summary
To update, load the entity inside a transaction, and change it. Dirty checking saves the changes for you. Next, partial updates with PATCH.
Key takeaways- findById().orElseThrow
- Change the fields
- Dirty checking