1 package ejava.examples.blpurchase.blimpl; 2 3 import java.util.List; 4 5 import javax.persistence.EntityManager; 6 import javax.persistence.TypedQuery; 7 8 import org.slf4j.Logger; 9 import org.slf4j.LoggerFactory; 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 Logger logger = LoggerFactory.getLogger(CatalogImpl.class); 18 private EntityManager em; 19 20 public void setEntityManager(EntityManager entityManager) { 21 em = entityManager; 22 } 23 24 @Override 25 public List<Product> getProducts(int offset, int limit) { 26 TypedQuery<Product> query = em.createNamedQuery(Product.GET_PRODUCTS_QUERY, Product.class); 27 if (offset > 0) { 28 query.setFirstResult(offset); 29 } 30 if (limit > 0) { 31 query.setMaxResults(limit); 32 } 33 return query.getResultList(); 34 } 35 36 @Override 37 public int addToCart(int id, String email) { 38 Product product = em.find(Product.class, id); 39 if (product == null) { 40 logger.warn("product not found: {}", id); 41 return 0; 42 } 43 if (product.getCount()-1 < 0) { 44 logger.warn("no product left"); 45 return 0; 46 } 47 product.setCount(product.getCount()-1); 48 49 Cart cart = em.find(Cart.class, email); 50 if (cart == null) { 51 List<Account> accounts = em.createNamedQuery( 52 Account.FIND_BY_EMAIL_QUERY, Account.class) 53 .setParameter("email", email) 54 .getResultList(); 55 if (accounts.size() == 0) { 56 logger.warn("no account found for: {}", email); 57 return 0; 58 } 59 cart = new Cart(accounts.get(0)); 60 em.persist(cart); 61 } 62 cart.getProducts().add(product); 63 64 return cart.getProducts().size(); 65 } 66 }