首页 > 解决方案 > 以表格形式访问数据库

问题描述

正在为我正在建设的项目而苦苦挣扎。我是 Java 新手,这只是我为练习而准备的东西。这是一种形式,是收银机的一部分。您将选择一个项目并将其添加到卡中。我的问题在于getById()方法,在线:for ( Inventory candidateItem : inventoryDao.findAll()). 具体来说inventoryDao.findAll()。这是对我创建的数据库的调用,它在我的控制器中工作,但在这里不起作用。我觉得可能与那个“静态”有关,因为我可以删除它,但它会破坏其他东西。

public class Cart {

@Autowired
    private InventoryDao inventoryDao;

    static ArrayList<Inventory> cart = new ArrayList<>();


    public static ArrayList<Inventory> getAll() {
        return cart;
    }



    public static void add(int id) {
        Inventory cartItemToAdd = getById(id);
        cart.add(cartItemToAdd);
    }

    public static void remove(int id) {
        Inventory cartItemToRemove = getById(id);
        cart.remove(cartItemToRemove);
    }

    //Issue is here.....
    public static Inventory getById(int id) {

        Inventory theItem = null;
        // InventoryDao inventoryDao = null;
        for ( Inventory candidateItem : inventoryDao.findAll()) {  //<---here
            if (candidateItem.getId() == id) {
                theItem = candidateItem;
            }
        }
        return theItem;
    }

    public static void clearCart() { //this shoud effective reset teh array list. Used when sending the completed order to DB or just clearing car
        ArrayList<Inventory> cart = new ArrayList<>();
    }

}

标签: java

解决方案


推荐阅读