1 package ejava.examples.webtier.jpa; 2 3 import java.util.Iterator; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.persistence.EntityManager; 8 import javax.persistence.Query; 9 10 import org.apache.commons.logging.Log; 11 import org.apache.commons.logging.LogFactory; 12 13 import ejava.examples.webtier.bo.Student; 14 import ejava.examples.webtier.dao.StudentDAO; 15 import ejava.examples.webtier.dao.StudentDAOException; 16 17 public class StudentJPADAO implements StudentDAO { 18 Log log = LogFactory.getLog(StudentJPADAO.class); 19 20 public Student create(Student student) throws StudentDAOException { 21 try { 22 JPAUtil.getEntityManager().persist(student); 23 } 24 catch (Throwable ex) { 25 throw new StudentDAOException(ex); 26 } 27 return student; 28 } 29 30 @SuppressWarnings("unchecked") 31 public List<Student> find(int index, int count) throws StudentDAOException { 32 try { 33 return JPAUtil.getEntityManager().createQuery( 34 "select s from Student s " + 35 "").setFirstResult(index) 36 .setMaxResults(count) 37 .getResultList(); 38 } 39 catch (Throwable ex) { 40 throw new StudentDAOException(ex); 41 } 42 } 43 44 @SuppressWarnings("unchecked") 45 public List<Student> find( 46 String name, Map<String, Object> args, int index, int count) 47 throws StudentDAOException { 48 try { 49 log.debug("named query:" + name + 50 ", index=" + index + ", count=" + count); 51 Query query = JPAUtil.getEntityManager().createNamedQuery(name); 52 if (query != null && args!=null) { 53 for(Iterator<String> itr=args.keySet().iterator(); 54 itr.hasNext();) { 55 String key = itr.next(); 56 Object value = args.get(key); 57 query.setParameter(key, value); 58 log.debug("key=" + key + ", value=" + value); 59 } 60 } 61 return query.setFirstResult(index) 62 .setMaxResults(count) 63 .getResultList(); 64 } 65 catch (StudentDAOException ex) { 66 throw new StudentDAOException(ex); 67 } 68 } 69 70 public List<Student> find(String name, int index, int count) 71 throws StudentDAOException { 72 return find(name, null, index, count); 73 } 74 75 public Student get(long id) throws StudentDAOException { 76 try { 77 return JPAUtil.getEntityManager().find(Student.class, id); 78 } 79 catch (StudentDAOException ex) { 80 throw new StudentDAOException(ex); 81 } 82 } 83 84 public Student remove(Student student) throws StudentDAOException { 85 try { 86 JPAUtil.getEntityManager().remove(student); 87 return student; 88 } 89 catch (StudentDAOException ex) { 90 throw new StudentDAOException(ex); 91 } 92 } 93 94 public Student update(Student student) throws StudentDAOException { 95 try { 96 EntityManager em = JPAUtil.getEntityManager(); 97 return em.merge(student); 98 } 99 catch (StudentDAOException ex) { 100 throw new StudentDAOException(ex); 101 } 102 } 103 }