1 package ejava.examples.asyncmarket.jpa;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Map;
6
7 import javax.persistence.EntityManager;
8 import javax.persistence.Query;
9
10 import ejava.examples.asyncmarket.bo.AuctionItem;
11 import ejava.examples.asyncmarket.bo.Bid;
12 import ejava.examples.asyncmarket.dao.AuctionItemDAO;
13
14 public class JPAAuctionItemDAO implements AuctionItemDAO {
15 private EntityManager em;
16
17 public void setEntityManager(EntityManager em) {
18 this.em = em;
19 }
20
21 public AuctionItem getItem(long itemId) {
22 return em.find(AuctionItem.class, itemId);
23 }
24
25 public AuctionItem createItem(AuctionItem item) {
26 em.persist(item);
27 return item;
28 }
29
30 public AuctionItem updateItem(AuctionItem item) {
31 return em.merge(item);
32 }
33
34 public Bid addBid(long itemId, Bid bid) {
35 AuctionItem item = em.find(AuctionItem.class, itemId);
36 bid.setItem(item);
37 item.getBids().add(bid);
38 em.persist(bid);
39 return bid;
40 }
41
42 @SuppressWarnings("unchecked")
43 public List<AuctionItem> getItems(int index, int count) {
44 Query query = em.createNamedQuery("AsyncMarket_getAuctionItems")
45 .setFirstResult(index)
46 .setMaxResults(count);
47 return query.getResultList();
48 }
49
50 @SuppressWarnings("unchecked")
51 public List<AuctionItem> getAvailableItems(int index, int count) {
52 Query query = em.createNamedQuery("AsyncMarket_getAvailableAuctionItems")
53 .setFirstResult(index)
54 .setMaxResults(count);
55 return query.getResultList();
56 }
57
58 @SuppressWarnings("unchecked")
59 public List<AuctionItem> getItems(
60 String queryString, Map<String, Object> params,
61 int index, int count) {
62 Query query = em.createNamedQuery(queryString)
63 .setFirstResult(index)
64 .setMaxResults(count);
65 if (params != null && params.size() != 0) {
66 for (String name: params.keySet()) {
67 query.setParameter(name, params.get(name));
68 }
69 }
70 return query.getResultList();
71 }
72
73 public void removeItem(long id) {
74 AuctionItem item = getItem(id);
75
76 List<Bid> bids = new ArrayList<Bid>(item.getBids());
77 for (Bid bid : bids) {
78 bid.getBidder().getBids().remove(bid);
79 item.getBids().remove(bid);
80 em.remove(bid);
81 }
82 item.getOwner().getItems().remove(item);
83 em.createQuery("delete from Order o " +
84 "where o.item.id = :itemId")
85 .setParameter("itemId", id)
86 .executeUpdate();
87 em.remove(item);
88 }
89
90 public Bid getBid(long bidId) {
91 return em.find(Bid.class, bidId);
92 }
93
94 public void removeBid(Bid bid) {
95 bid.getBidder().getBids().remove(bid);
96 bid.getItem().getBids().remove(bid);
97 em.remove(bid);
98 }
99 }