View Javadoc
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.slf4j.Logger;
11  import org.slf4j.LoggerFactory;
12  
13  import ejava.examples.webtier.bo.Student;
14  import ejava.examples.webtier.dao.StudentDAO;
15  
16  public class StudentJPADAO implements StudentDAO {
17      private Logger logger = LoggerFactory.getLogger(StudentJPADAO.class);
18      private EntityManager em;
19  
20      public void setEntityManager(EntityManager em) {
21          this.em = em;
22      }
23      
24      public Student create(Student student) {
25          em.persist(student);
26          return student;
27      }
28  
29      @SuppressWarnings("unchecked")
30      public List<Student> find(int index, int count) {
31          return em.createQuery(
32                  "select s from Student s")
33          		       .setFirstResult(index)
34                     .setMaxResults(count)
35                     .getResultList();
36      }
37  
38      @SuppressWarnings("unchecked")
39      public List<Student> find(
40              String name, Map<String, Object> args, int index, int count) {
41          logger.debug("named query:" + name + 
42                  ", index=" + index + ", count=" + count);
43          Query query = em.createNamedQuery(name);
44          if (query != null && args!=null) {
45              for(Iterator<String> itr=args.keySet().iterator();
46                  itr.hasNext();) {
47                  String key = itr.next();
48                  Object value = args.get(key);
49                  query.setParameter(key, value);
50                  logger.debug("key=" + key + ", value=" + value);
51              }
52          }
53          return query.setFirstResult(index)
54                      .setMaxResults(count)
55                      .getResultList();
56      }
57  
58      public List<Student> find(String name, int index, int count) {
59          return find(name, null, index, count);
60      }
61  
62      public Student get(long id) {
63          return em.find(Student.class, id);
64      }
65  
66      public Student remove(Student student) {
67              em.remove(student);
68              return student;
69      }
70  
71      public Student update(Student student) {
72              return em.merge(student);
73      }
74  }