-
-
Save teuno/0bc170036418d23071c05b2f38189763 to your computer and use it in GitHub Desktop.
ProductRestController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestController | |
@RequestMapping("/products") | |
public class ProductRestController { | |
private final ProductRepository productRepository; | |
public ProductRestController(ProductRepository productRepository) { | |
this.productRepository = productRepository; | |
} | |
@GetMapping | |
public Iterable<Product> getProducts() { | |
return productRepository.findAll(); | |
} | |
@GetMapping("/{id}") | |
public ResponseEntity<Object> getProduct(@PathVariable Long id) { | |
Product product = productRepository.findOne(id); | |
if (product == null) { | |
return new ResponseEntity<>("No Product found with id " + id, HttpStatus.NOT_FOUND); | |
} | |
return new ResponseEntity<>(product, HttpStatus.OK); | |
} | |
@PostMapping | |
public ResponseEntity<Product> createProduct(@RequestBody Product product) { | |
productRepository.save(product); | |
return new ResponseEntity<>(product, HttpStatus.OK); | |
} | |
@PutMapping("/{id}") | |
public ResponseEntity<String> updateProduct(@PathVariable Long id, @RequestBody Product product) { | |
Product p = productRepository.findOne(id); | |
if (null == p) { | |
return new ResponseEntity<>("No Product found with id " + id, HttpStatus.NOT_FOUND); | |
} | |
p.setName(product.getName()); | |
p.setPrice(product.getPrice()); | |
productRepository.save(p); | |
return new ResponseEntity<>("Product with " +id+ " has been updated", HttpStatus.OK); | |
} | |
@DeleteMapping("/{id}") | |
public ResponseEntity<String> deleteProduct(@PathVariable Long id) { | |
if (null == productRepository.findOne(id)) { | |
return new ResponseEntity<>("No Product found with id " + id, HttpStatus.NOT_FOUND); | |
} | |
productRepository.delete(id); | |
return new ResponseEntity<>("Product with id " +id+ " is removed", HttpStatus.OK); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment