I have a spring boot program and right now my PutMapping function seems not be working as expected. Right now if I update the field in postman it says no errors but when I checked to see if the update occurred then there are no changes.
Controller:
@PutMapping(path = "{bookingId}")
public void updateBooking (
@PathVariable("bookingId") Long bookingId,
@RequestParam(required = false) Integer tickets ) {
bookingService.updateBooking(bookingId, tickets);
}
Service:
public void updateBooking(Long bookingId, Integer tickets) {
// checks if event id exists
Booking booking = bookingRepository.findById(bookingId).orElseThrow(() -> new IllegalStateException(
"Booking with id " bookingId " does not exists. "));
if (tickets != null && !Objects.equals(booking.getTickets(), tickets)) {
booking.setTickets(tickets);
booking.setAmount(booking.getAmount());
}
else {
throw new IllegalStateException(
"The update was unsuccessful" );
}
}
Model:
public Integer getTickets() {
return tickets;
}
public void setTickets(Integer tickets) {
this.tickets = tickets;
}
CodePudding user response:
You are not saving the updated object in the database.
public void updateBooking(Long bookingId, Integer tickets) {
// checks if event id exists
Booking booking = bookingRepository.findById(bookingId).orElseThrow(() -> new IllegalStateException(
"Booking with id " bookingId " does not exists. "));
if (tickets != null && !Objects.equals(booking.getTickets(), tickets)) {
booking.setTickets(tickets);
booking.setAmount(booking.getAmount());
// save the updated booking in the database
bookingRepository.save(booking)
}
else {
throw new IllegalStateException(
"The update was unsuccessful" );
}
}