public List<Myshopee_ProductTO> getProductsFromCategory(char category) throws NoProductInCategoryException, Exception { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Group4"); EntityManager em = null; List<Myshopee_ProductTO> productTOList = new ArrayList<Myshopee_ProductTO>(); try { em = emf.createEntityManager(); Query query = em.createQuery("select p from Myshopee_Product p where p.category = ?1"); query.setParameter(1, category); List<Object> productList = query.getResultList(); if (productList == null || productList.isEmpty()) { throw new NoProductInCategoryException(); } for (Object object : productList) { Myshopee_Product product = (Myshopee_Product) object; Myshopee_ProductTO productTO = new Myshopee_ProductTO(); productTO.setProductId(product.getProductId()); productTO.setProductName(product.getProductName()); productTO.setAssociatedPoints(product.getAssociated_points()); productTO.setQtyInStock(product.getQtyInStock()); productTO.setPricePerUnit(product.getPricePerUnit()); productTO.setCategory(product.getCategory()); // adding to the list of productTO productTOList.add(productTO); } } catch (NoProductInCategoryException e) { ErrorLogger.logError(this.getClass().getName(), "getProductsFromCategory", e.getMessage()); throw e; } catch (Exception e) { ErrorLogger.logError(this.getClass().getName(), "getProductsFromCategory", e.getMessage()); throw e; } finally { if (em != null) { em.close(); } } return productTOList; }
@SuppressWarnings("unchecked") public List<Myshopee_ProductTO> getProductFromCategory(char category) throws Exception { EntityManager em = null; try { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Group4"); List<Myshopee_Product> list = new ArrayList<Myshopee_Product>(); List<Myshopee_ProductTO> list1 = new ArrayList<Myshopee_ProductTO>(); em = emf.createEntityManager(); Query query = em.createQuery("select p from Myshopee_Product p where p.category=?1"); query.setParameter(1, category); list = query.getResultList(); if (list.size() != 0) { for (int index = 0; index < list.size(); index++) { Myshopee_Product product = new Myshopee_Product(); Myshopee_ProductTO productTO = new Myshopee_ProductTO(); product = (Myshopee_Product) list.get(index); productTO.setProductId(product.getProductId()); productTO.setProductName(product.getProductName()); productTO.setAssociatedPoints(productTO.getAssociatedPoints()); productTO.setQtyInStock(product.getQtyInStock()); productTO.setCategory(product.getCategory()); productTO.setPricePerUnit(product.getPricePerUnit()); list1.add(productTO); } return list1; } else { throw new NoProductInCategoryException(); } } catch (NoProductInCategoryException e) { ErrorLogger.logError(this.getClass().getName(), "getProductFromCategory", e.getMessage()); throw e; } catch (Exception e) { ErrorLogger.logError(this.getClass().getName(), "getProductFromCategory", e.getMessage()); throw e; } finally { if (em != null) em.close(); } }