0
我有一個函數來驗證購物車中物品的存在。我的當前代碼以這種方式工作,如果代碼返回異常,則表示商品不存在於購物車中。如何使用Hibernate查找購物車中是否有商品?
問題是,如果當前代碼返回任何類型的異常,我把它作爲項目不在列表中。
如何更改代碼的方式,如果物品不在購物車中?
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;
}
這是錯誤的,因爲如果該項目不在車中,代碼拋出將由catch塊,因此返回3 – AlexCartio1
@ AlexCartio1我被捕獲的異常:像You'de最好加一個枚舉編輯我的答案並添加了整個代碼。 –