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.TypedQuery; 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 List<Person> results = em.createNamedQuery(GET_PEOPLE_BY_USERID, Person.class) 27 .setParameter("userId", userId) 28 .getResultList(); 29 return results.isEmpty() ? null : results.get(0); 30 } 31 32 public Person createPerson(Person person) { 33 em.persist(person); 34 return person; 35 } 36 37 public void removePerson(Person person) { 38 em.remove(person); 39 } 40 41 public List<Person> getPeople(int index, int count) { 42 return em.createNamedQuery(GET_ALL_PEOPLE, Person.class) 43 .setFirstResult(index) 44 .setMaxResults(count) 45 .getResultList(); 46 } 47 48 public List<Person> getPeople( 49 String queryString, Map<String, Object> params, int index, int count) { 50 TypedQuery<Person> query = em.createNamedQuery(GET_PEOPLE_BY_USERID, Person.class) 51 .setFirstResult(index) 52 .setMaxResults(count); 53 if (params != null && params.size() != 0) { 54 for (String name: params.keySet()) { 55 query.setParameter(name, params.get(name)); 56 } 57 } 58 return query.getResultList(); 59 } 60 61 }