1 package ejava.examples.ejbsessionbank.jpa;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8
9 import javax.persistence.EntityManager;
10 import javax.persistence.Query;
11
12 import org.apache.commons.logging.Log;
13 import org.apache.commons.logging.LogFactory;
14
15 import ejava.examples.ejbsessionbank.bo.Account;
16 import ejava.examples.ejbsessionbank.bo.Owner;
17 import ejava.examples.ejbsessionbank.dao.DAOException;
18 import ejava.examples.ejbsessionbank.dao.OwnerDAO;
19
20 public class JPAOwnerDAO implements OwnerDAO {
21 static final Log log = LogFactory.getLog(JPAOwnerDAO.class);
22
23 static final String COUNT_ACCOUNT_REFERENCES_QUERY =
24 "countAccountReferences";
25
26 private EntityManager em;
27
28 public void setEntityManager(EntityManager em) {
29 this.em = em;
30 }
31
32 public Owner createOwner(Owner owner) throws DAOException {
33 em.persist(owner);
34 return owner;
35 }
36
37 @SuppressWarnings("unchecked")
38 public List<Owner> findOwners(String queryName, Map<String, Object> params,
39 int index, int count) throws DAOException {
40 Query query = em.createNamedQuery(queryName);
41 if (params != null && params.size() > 0) {
42 for (String key : params.keySet()) {
43 Object value = params.get(key);
44 query.setParameter(key, value);
45 }
46 }
47 return query.setFirstResult(index)
48 .setMaxResults(count)
49 .getResultList();
50 }
51
52 public Owner getOwnerById(long id) throws DAOException {
53 return em.find(Owner.class, id);
54 }
55
56 public Owner removeOwner(Owner owner) throws DAOException {
57 if (!em.contains(owner)) {
58 owner = em.find(Owner.class, owner.getId());
59 }
60 if (owner != null) {
61 Collection<Account> accounts = new ArrayList<Account>();
62 accounts.addAll(owner.getAccounts());
63 for (Account a: accounts) {
64 owner.getAccounts().remove(a);
65
66
67 if (((Long)em.createNamedQuery(COUNT_ACCOUNT_REFERENCES_QUERY)
68 .setParameter("account", a)
69 .getSingleResult()) == 0) {
70 em.remove(a);
71 }
72 }
73 em.remove(owner);
74 }
75 return owner;
76 }
77
78 public List<Owner> getAccountOwners(Account account) throws DAOException {
79 Map<String, Object> params = new HashMap<String, Object>();
80 params.put("account", account);
81 List<Owner> owners =
82 findOwners("getAccountOwner", params, 0, 100);
83 return owners;
84 }
85 }