Question

I have a function to verify the existence of an item in the cart. My current code works in this way, if the code returns an exception it means the item does not exist in the cart.

The problem is that, if the current code returns any type of exception I take it as item is not in the list.

How can I change the code in a way that if an item is not in the cart?

  Criteria cre = session.createCriteria(Cart.class, "cart")
                        .createAlias("cart.items", "items")
                        .createAlias("items.pro", "pro");
                cre.add(Restrictions.eq("cart.id", cartId));
                cre.add(Restrictions.eq("pro.id", proId));
                Cart cart = (Cart) cre.list().get(0);
                if (!tx.wasCommitted()) {
                    tx.commit();
                }
                if (session.isOpen()) {
                    session.close();
                }
                if (cart.getItems().size() >= 1) {
                    System.err.println("Item is in the cart");
                    return 1;
                }
            } catch (Exception e) {
                System.err.println("either item is not in the cart or an exception was thrown");
                return 2;     
            }
Was it helpful?

Solution

    Criteria cre = session.createCriteria(Cart.class, "cart")
        .createAlias("cart.items", "items")
        .createAlias("items.pro", "pro");
        cre.add(Restrictions.eq("cart.id", cartId));
        cre.add(Restrictions.eq("pro.id", proId));
    List<Cart> carts = cre.list();
    if (carts.size() == 0)
        return 2; //ItemReteieveStatus.NOT_FOUND;

    Cart cart = carts.get(0);
    if (!tx.wasCommitted()) {
        tx.commit();
    }
    if (session.isOpen()) {
        session.close();
    }
    if (cart.getItems().size() >= 1) {
        System.err.println("Item is in the cart");
        return 1;//ItemReteieveStatus.FOUND;
    }
    return 2;//ItemReteieveStatus.NOT_FOUND
} catch (Exception e) {
    System.err.println("either item is not in the cart or an exception was thrown");
    return 3;//ItemReteieveStatus.ERROR;     
}

And it is not a good practice to return integers. You'de better add an enum like:

public enum ItemReteieveStatus {
    FOUND, NOT_FOUNT, ERROR;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top