Restaurant Update Service
In this lesson, we'll implement the complete update functionality for restaurants in our service layer, building on our previous design decisions and exception handling setup.
Full Update Implementation
The full update approach means that when a restaurant is updated, all fields are replaced with the new values provided in the request.
Let's break down the implementation of the updateRestaurant method in RestaurantServiceImpl:
@Override
public Restaurant updateRestaurant(String id, RestaurantCreateUpdateRequest restaurantCreateUpdateRequest) {
// First, verify the restaurant exists
Restaurant existingRestaurant = getRestaurant(id)
.orElseThrow(() -> new RestaurantNotFoundException("Restaurant with ID does not exist: " + id));
// Get new geo coordinates based on the updated address
GeoLocation newGeoLocation = geoLocationService.geoLocate(restaurantCreateUpdateRequest.getAddress());
GeoPoint newGeoPoint = new GeoPoint(newGeoLocation.getLatitude(), newGeoLocation.getLongitude());
// Convert photo URLs to Photo entities
List<Photo> photos = restaurantCreateUpdateRequest.getPhotoIds().stream().map(photoUrl ->
Photo.builder()
.url(photoUrl)
.uploadDate(LocalDateTime.now())
.build()
).collect(Collectors.toList());
// Update all fields except averageRating
existingRestaurant.setName(restaurantCreateUpdateRequest.getName());
existingRestaurant.setCuisineType(restaurantCreateUpdateRequest.getCuisineType());
existingRestaurant.setContactInformation(restaurantCreateUpdateRequest.getContactInformation());
existingRestaurant.setAddress(restaurantCreateUpdateRequest.getAddress());
existingRestaurant.setGeoLocation(newGeoPoint);
existingRestaurant.setOperatingHours(restaurantCreateUpdateRequest.getOperatingHours());
existingRestaurant.setPhotos(photos);
return restaurantRepository.save(existingRestaurant);
}Error Handling
As designed in our previous lesson, we use the RestaurantNotFoundException when a restaurant with the provided ID doesn't exist.
The exception is thrown through the .orElseThrow() method when getRestaurant() returns an empty Optional.
Data Preservation
Notice that we maintain the restaurant's averageRating during updates.
This is important because the rating is calculated from user reviews and shouldn't be affected by restaurant information updates.
Summary
- Implemented full update method in
RestaurantServiceImpl - Used
RestaurantNotFoundExceptionwhen restaurant not found - Preserved
averageRatingduring updates