1

I have customers and books in my table. When a customer is deleted I also want book's availability to be set to available. When I only execute the code without first 3 lines of the method(setting availability to the available) it works perfectly fine and deletes the customer object. But when I add those lines to set books available then nothing happens and customer object stays without any removal.

@GetMapping("/customers/delete/{id}")
public String deleteCustomer(@PathVariable("id") int theId, Model model){
    Customer c1 = CustomerService.getSingleCustomer(theId).get();
    for(int i=0;i<c1.getRentedBooks().size();i++){
        c1.getRentedBooks().get(i).availability="Available";
    }
   

    CustomerService.delete(theId);
    return "redirect:/customer/listofcustomers";
}
5
  • 1
    For starters this code needs to be in a service not in a controller. Second do you have a bi-directional relationship between book and customer? If so the update on book will re-instate the customer. Commented Dec 16, 2021 at 12:43
  • I get the idea that any update will re-instate the customer but the thing is I do update operations before deleting the customer. So in my perspective nothing should change considering the order of the execution. What is the correct way of doing what I aimed for. Thank you in advance for your comment Commented Dec 16, 2021 at 12:53
  • Everything is flushed at once instead of single operations. What you should do is set the customer to null in the books, change the status and delete the user. And as stated this code should be in service method not a controller method. YOur controller should call that transactional service method. Commented Dec 16, 2021 at 12:58
  • Is CustomerService a class or a poor variable identifier?? ;(;(;( Commented Dec 16, 2021 at 13:36
  • Hey Deinum, The problem was I never set Book's customer attribute to null. I have moved my code to service method and set customer to null while deletion as you have told me. It worked like a charm. Thanks for taking your time and helping me out Commented Dec 16, 2021 at 14:14

1 Answer 1

1

If field availability in Book class is private, use:

c1.getRentedBooks().get(i).setAvailability("Available");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.