Bird
0
0

Which combination of annotations and code best achieves this using @PutMapping?

hard📝 Application Q15 of 15
Spring Boot - REST Controllers
You want to implement a REST API in Spring Boot that updates a product's price only if the product exists, otherwise returns 404. Which combination of annotations and code best achieves this using @PutMapping?
A@PutMapping("/products/{id}") public Product updatePrice(@RequestParam int id, @RequestBody Product p) { p.setId(id); return productService.save(p); }
B@PutMapping("/products") public Product updatePrice(@RequestBody Product p) { productService.save(p); return p; }
C@PutMapping("/products/{id}") public void updatePrice(@PathVariable int id, @RequestBody Product p) { productService.save(p); }
D@PutMapping("/products/{id}") public ResponseEntity<Product> updatePrice(@PathVariable int id, @RequestBody Product p) { return productService.findById(id) .map(existing -> { existing.setPrice(p.getPrice()); productService.save(existing); return ResponseEntity.ok(existing); }) .orElse(ResponseEntity.notFound().build()); }
Step-by-Step Solution
Solution:
  1. Step 1: Check for product existence before update

    @PutMapping("/products/{id}") public ResponseEntity updatePrice(@PathVariable int id, @RequestBody Product p) { return productService.findById(id) .map(existing -> { existing.setPrice(p.getPrice()); productService.save(existing); return ResponseEntity.ok(existing); }) .orElse(ResponseEntity.notFound().build()); } uses productService.findById(id) to check if product exists, returning 404 if not.
  2. Step 2: Update price only if product found and return proper HTTP response

    The map lambda updates the price on the existing product, saves it, and returns ResponseEntity.ok(existing); orElse returns notFound().
  3. Final Answer:

    @PutMapping("/products/{id}") public ResponseEntity updatePrice(@PathVariable int id, @RequestBody Product p) { return productService.findById(id) .map(existing -> { existing.setPrice(p.getPrice()); productService.save(existing); return ResponseEntity.ok(existing); }) .orElse(ResponseEntity.notFound().build()); } -> Option D
  4. Quick Check:

    Check existence, update, return 404 if missing [OK]
Quick Trick: Check existence first, then update and return ResponseEntity [OK]
Common Mistakes:
  • Not checking if product exists before update
  • Using @RequestParam instead of @PathVariable for ID
  • Not returning 404 when product missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes