1 package ejava.examples.asyncmarket.jpa; 2 3 import java.util.List; 4 import java.util.Map; 5 6 import javax.persistence.EntityManager; 7 import javax.persistence.Query; 8 9 import ejava.examples.asyncmarket.bo.Order; 10 import ejava.examples.asyncmarket.dao.OrderDAO; 11 12 public class JPAOrderDAO implements OrderDAO { 13 private EntityManager em; 14 15 public void setEntityManager(EntityManager em) { 16 this.em = em; 17 } 18 19 public Order createOrder(Order order) { 20 em.persist(order); 21 return order; 22 } 23 24 public Order getOrder(long orderId) { 25 return em.find(Order.class, orderId); 26 } 27 28 @SuppressWarnings("unchecked") 29 public List<Order> getOrdersforItem(long itemId, int index, int count) { 30 return em.createNamedQuery("AsyncMarket_getOrdersForItem") 31 .setParameter("itemId", itemId) 32 .setFirstResult(index) 33 .setMaxResults(count) 34 .getResultList(); 35 } 36 37 @SuppressWarnings("unchecked") 38 public List<Order> getOrders(int index, int count) { 39 return em.createNamedQuery("AsyncMarket_getOrders") 40 .getResultList(); 41 } 42 43 public Order updateOrder(Order order) { 44 return em.merge(order); 45 } 46 47 @SuppressWarnings("unchecked") 48 public List<Order> getOrders( 49 String queryString, Map<String, Object> params, int index, int count) { 50 Query query = em.createQuery(queryString) 51 .setFirstResult(index) 52 .setMaxResults(count); 53 if (params != null) { 54 for (String name: params.keySet()) { 55 query.setParameter(name, params.get(name)); 56 } 57 } 58 return query.getResultList(); 59 } 60 }