Hello there!
I have a question about how a certain interaction of spring annotations works. I am working on the dining review API right now and this is what I came across -
In my Restaurant Controller I want a Post method to post a new restaurant, which is easy enough. I just use @RequestBody to register a new entry in the database. BEFORE I do that though I want to check if a restaurant with the same name and ZipCode already exists. Is there a way to “extract” those informations off of the request body or do I need to add additional @RequestParams, and how would that work and affect the curl commands? This is my code so far but I am not sure if it would work the way I intend it to:
@PostMapping("/")
public Restaurant addNewRestaurant(@RequestBody Restaurant restaurant, @RequestParam String name, @RequestParam Long zipCode ) {
Optional<Restaurant> checkForExistingRestaurants = this.restaurantRepository.findByRestaurantNameAndZipcode(name, zipCode);
if (checkForExistingRestaurants.isPresent()) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Restaurant already exists");
} else {
Restaurant newRestaurant = this.restaurantRepository.save(restaurant);
return newRestaurant;
}
}
Non codebyte:
@PostMapping("/")
public Restaurant addNewRestaurant(@RequestBody Restaurant restaurant, @RequestParam String name, @RequestParam Long zipCode ) {
Optional<Restaurant> checkForExistingRestaurants = this.restaurantRepository.findByRestaurantNameAndZipcode(name, zipCode);
if (checkForExistingRestaurants.isPresent()) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Restaurant already exists");
} else {
Restaurant newRestaurant = this.restaurantRepository.save(restaurant);
return newRestaurant;
}
}