@RequestMapping("{id}/remove") public ModelAndView remove(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) { List<Cart> carts = cartRepository.findByProductId(id); boolean okToErase = true; for (Cart cart : carts) { if (isCartToOld(cart.getCreated())) { removeCart(cart); } else { okToErase = false; } } if (okToErase) { productRepository.delete(id); redirectAttributes.addFlashAttribute("globalMessage", "Successfully deleted product"); } else { redirectAttributes.addFlashAttribute( "globalMessage", "Can't delete product, there are still carts with them."); } return new ModelAndView("redirect:/products"); }