To make GET /products fast, the shop keeps the product list in a HashMap called cache. The first request reads the database and remembers the list; every later one answers from memory. An AI assistant wrote the route that changes a price:
@PatchMapping("/products/{productId}")
Object changePrice(@PathVariable int productId, @RequestBody Map<String, Object> data) {
int updated = db.update("UPDATE products SET price = ? WHERE id = ?", data.get("price"), productId);
if (updated == 0) {
return ResponseEntity.status(404).body(Map.of("error", "Product not found"));
}
return Map.of("id", productId, "price", data.get("price"));
}
The new price is saved, but nobody tells the cache. After PATCH /products/1 sets the Mug to 14, GET /products keeps answering the list it remembered, with the Mug at 12, until the app restarts. The remembered list is stale: true once, wrong now.
The rule for any cache: every route that changes the data clears what was remembered about it. If the shop also cached its categories, the route that adds one would forget that list:
@PostMapping("/categories")
Object addCategory(@RequestBody Map<String, Object> data) {
db.update("INSERT INTO categories (name) VALUES (?)", data.get("name"));
cache.remove("categories"); // forget the remembered list
return ResponseEntity.status(201).body(Map.of("name", data.get("name")));
}
cache.remove(key) forgets one key, and cache.clear() empties the whole map. The requests and the answers your app must give:
GET /products → 200 [{"id": 1, "name": "Mug", "price": 12}, {"id": 2, "name": "Notebook", "price": 7}, …] (8 products)
PATCH /products/1 {"price": 14} → 200 {"id": 1, "price": 14}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14}, {"id": 2, "name": "Notebook", "price": 7}, …]
PATCH /products/99 {"price": 5} → 404 {"error": "Product not found"}
PATCH /products/4 {"price": 3} → 200 {"id": 4, "price": 3}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14}, …, {"id": 4, "name": "Pen", "price": 3}, …]
Your task: rewrite changePrice. Save the new price, answer 404 when no product has that id, empty the cache after a real change, and answer the id and the new price.
Assignment
Follow the Coding Tutorial to rewrite changePrice so the shop shows every new price at once.
Hint
The line the AI forgot is cache.clear();. Put it after the 404 check: when no product changed, the remembered list is still true, so there is nothing to forget.
Free plan: 30 tutor messages. PRO is unlimited.
