1 package ejava.examples.blpurchase.blimpl; 2 3 import java.util.List; 4 5 import javax.persistence.EntityManager; 6 import javax.persistence.Query; 7 8 import org.apache.commons.logging.Log; 9 import org.apache.commons.logging.LogFactory; 10 11 import ejava.examples.blpurchase.bl.Catalog; 12 import ejava.examples.blpurchase.bo.Account; 13 import ejava.examples.blpurchase.bo.Cart; 14 import ejava.examples.blpurchase.bo.Product; 15 16 public class CatalogImpl implements Catalog { 17 private static final Log log = LogFactory.getLog(CatalogImpl.class); 18 private EntityManager em; 19 20 public void setEntityManager(EntityManager entityManager) { 21 em = entityManager; 22 } 23 24 @SuppressWarnings("unchecked") 25 @Override 26 public List<Product> getProducts(int offset, int limit) { 27 Query query = em.createQuery("select p from Product p"); 28 if (offset > 0) { 29 query.setFirstResult(offset); 30 } 31 if (limit > 0) { 32 query.setMaxResults(limit); 33 } 34 return query.getResultList(); 35 } 36 37 @Override 38 public int addToCart(int id, String email) { 39 Product product = em.find(Product.class, id); 40 if (product == null) { 41 log.warn("product not found:" + id); 42 return 0; 43 } 44 if (product.getCount()-1 < 0) { 45 log.warn("no product left"); 46 return 0; 47 } 48 product.setCount(product.getCount()-1); 49 50 Cart cart = em.find(Cart.class, email); 51 if (cart == null) { 52 List<Account> accounts = em.createNamedQuery( 53 Account.FIND_BY_EMAIL, Account.class) 54 .setParameter("email", email) 55 .getResultList(); 56 if (accounts.size() == 0) { 57 log.warn("no account found for:" + email); 58 return 0; 59 } 60 cart = new Cart(accounts.get(0)); 61 em.persist(cart); 62 } 63 cart.getProducts().add(product); 64 65 return cart.getProducts().size(); 66 } 67 }