Spring Boot 我无法从购物车中删除项目

gorkyyrv  于 2023-03-18  发布在  Spring
关注(0)|答案(1)|浏览(138)

不从购物车中删除项目。当我点击“删除”的项目仍然存在。只执行总价格计算。购物车不是存储库,而小说项目是一个存储库实体,保存在数据库中感谢您的帮助这是我的代码:

@Component
public class Cart {

    private List <Fiction> fictions = new ArrayList<Fiction> ();
    
    private float totale = 0.0f;
        
        public Cart() {
        super();
    }
    
    
    public void add(Fiction fiction) {
        
        fictions.add(fiction);
        this.totale = totale + fiction.getPrezzo();
    }
    
    public void remove(Fiction fiction) {
        Iterator<Fiction> iterator = fictions.iterator();
        while(iterator.hasNext()) {
            Fiction item = iterator.next();
            if(item.equals(fiction)) {
                iterator.remove();
                }
        } this.totale = totale - fiction.getPrezzo();
    }

控制器

Does not remove items from cart.
When I hit "delete" the items are still there.
Only performs the total price calculation.
Thanks for your help
This is my code :  

@Controller
public class CartController {

    @Autowired
    Cart carrello;
    
    @Autowired
    private FictionRepo fictionRepo;
    
  
    
    @RequestMapping("/deleteToCart/{id}")
    public String deleteToCart(@PathVariable("id") Long id ) {
        Fiction fictions = fictionRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("Fiction non trovata"));
        System.out.println(" sto per cancellare");
        carrello.remove(fictions);
        System.out.println(" ho cancellato");
        return "redirect:/indexCart";
    }

}
htrmnn0y

htrmnn0y1#

重写equals以使代码正常工作。请参考以下示例:

// Overriding equals() to compare two Fiction objects
  @Override
  public boolean equals(Object o) {

    // If the object is compared with itself then return true
    if (o == this) {
      return true;
    }

        /* Check if o is an instance of Fiction or not
          "null instanceof [type]" also returns false */
    if (!(o instanceof Fiction)) {
      return false;
    }

    // typecast o to Fiction so that we can compare data members
    Fiction c = (Fiction) o;

    // Compare the data members and return accordingly
    return this.id.equals(c.getId());
  }

相关问题