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.Person; 10 import ejava.examples.asyncmarket.dao.PersonDAO; 11 12 public class JPAPersonDAO implements PersonDAO { 13 private static final String GET_ALL_PEOPLE = "AsyncMarket_getAllPeople"; 14 private static final String GET_PEOPLE_BY_USERID = "AsyncMarket_getPersonByUserId"; 15 private EntityManager em; 16 17 public void setEntityManager(EntityManager em) { 18 this.em = em; 19 } 20 21 public Person getPerson(long personId) { 22 return em.find(Person.class, personId); 23 } 24 25 public Person getPersonByUserId(String userId) { 26 Query query = em.createNamedQuery(GET_PEOPLE_BY_USERID) 27 .setParameter("userId", userId); 28 return (Person)query.getSingleResult(); 29 } 30 31 public Person createPerson(Person person) { 32 em.persist(person); 33 return person; 34 } 35 36 public void removePerson(Person person) { 37 em.remove(person); 38 } 39 40 @SuppressWarnings("unchecked") 41 public List<Person> getPeople(int index, int count) { 42 Query query = em.createNamedQuery(GET_ALL_PEOPLE) 43 .setFirstResult(index) 44 .setMaxResults(count); 45 return query.getResultList(); 46 } 47 48 @SuppressWarnings("unchecked") 49 public List<Person> getPeople( 50 String queryString, Map<String, Object> params, int index, int count) { 51 Query query = em.createNamedQuery(GET_PEOPLE_BY_USERID) 52 .setFirstResult(index) 53 .setMaxResults(count); 54 if (params != null && params.size() != 0) { 55 for (String name: params.keySet()) { 56 query.setParameter(name, params.get(name)); 57 } 58 } 59 return query.getResultList(); 60 } 61 62 }