Search code examples
springspring-bootspring-mvcspring-data-jpaspring-data

Service method to store image for two different picture category


I have a project to store images for Rental property. The images would be for Bedroom and Bathroom.

Rental
BedroomImageId
BathroomImageId
// Service class method
public void uploadRentalImage(Long rentalId, MultipartFile file) {
     String imageId = UUID.randomUUID().toString(); // BedroomPictureId or BathroomPictureId will be created here
     // Then store the imageId to Rental; depending on whether it is BedroomPictureId or BathroomPictureId
}

I have two logics depedning on whether the image is BathroomImageId and BedroomImageId which I need to tell the uploadRentalImage. I have various ways in mind to tell the uploadRentalImage method as to which image I am updating. Could anyone recommend the best way of telling uploadRentalImage what type of image I am updating.

I could create two service class method like below but it would have too much of same logic repeating in both methods and is not scalable in future if I were to have more types of images like GarageImage or CourtyardImage.

public void uploadRentalImage(Long rentalId, MultipartFile file) {
     String imageId = UUID.randomUUID().toString(); // BedroomPictureId or BathroomPictureId will be created here
     rentalDao.updateBedroomImageId(bedroomImageId, rentalId);
}
public void uploadBathroomImage(Long rentalId, MultipartFile file) {
     String imageId = UUID.randomUUID().toString(); // BedroomPictureId or BathroomPictureId will be created here
     rentalDao.updateBedroomImageId(bedroomImageId, rentalId);
}

Solution

  • You can create a RentalImage class to store the reference to your images and ImageCategory enum to categorize your images, such as:

    public class RentalImage {
        private Long imageId;
        private String imageName;
        private String imageUrl;
        private ImageCategory category;
    }
    
    public enum ImageCategory {
       BEDROOM,
       BATHROOM
    }
    

    And, you can pass RentalImage object to the uploadRentalImage method. Now, this object has all the information needed to categorize the image.