'Best way to handle negative scenario in spring boot

So I am working on a spring-boot application for a zoo. while adding animals I can assign some room and mark some rooms as favorites, My sample JSON looks like below

{
   "id":null,
   "title":null,
   "located":null,
   "type":null,
   "preference":null,
   "favoriteRooms":null,
   "room":{
      "id":null,
      "title":"Green",
      "size":25,
      "createdOn":null,
      "favorites":null,
      "animals":null
   }
}

now I want to make sure the room should be valid while adding animals, if there is no room available I want to throw an error. currently, I am using CascadingType.MERGE but it throws hibernate exception I want to do some valid addition for room and favorite room what is the best way to do this? my entity class looks like below

@Entity
@Data
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class Animal {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_animal_id")
    @SequenceGenerator(name = "seq_animal_id")
    Long id;

    @NotEmpty(message = "title should be given")
    String title;

    @CreatedDate
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
    LocalDateTime located;

    String type;
    Long preference;

    @OneToMany(mappedBy = "animal")
    Set <Favorite> favoriteRooms;

    @ManyToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "room_id")
    Room room;
}


Solution 1:[1]

I'm not sure if I really understand what you're asking for but you can handle this in your controller or better in ServiceImplementation which handles the business logic.

Using @Valid the constraints will be checked which you have defined in your models:
example:

@Autowired
RoomRepository roomRepository;

@PostMapping
public ResponseEntity<?> insertAnimal(@Valid @RequestBody Animal animal) {

  Optional<Room> optionalRoom = roomRepository.findById(animal.getRoom.getRoomId());

  if (optionalRoom.isPresent()) {
   Room room = optionalRoom.get();
   // your logic to check if the room is valid
  }
  else {
    return new ResponseEntity<String>("Your message here", HttpStatus.NOT_FOUND);
  }
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 questioner