1 package ejava.examples.daoex.jpa;
2
3 import javax.persistence.EntityManager;
4 import javax.persistence.Query;
5
6 import org.apache.commons.logging.Log;
7 import org.apache.commons.logging.LogFactory;
8
9 import ejava.examples.daoex.AuthorDAO;
10 import ejava.examples.daoex.bo.Author;
11
12
13
14
15
16
17
18
19
20
21
22 public class JPAAuthorDAO implements AuthorDAO {
23 @SuppressWarnings("unused")
24 private static Log log_ = LogFactory.getLog(JPAAuthorDAO.class);
25 private EntityManager em;
26
27
28
29
30
31 public void setEntityManager(EntityManager em) {
32 this.em=em;
33 }
34
35
36
37
38 public void create(Author author) {
39 em.persist(author);
40 }
41
42
43
44
45 public Author get(long id) {
46 return em.find(Author.class, id);
47 }
48
49
50
51
52 public Author getByQuery(long id) {
53 Query query = em.createQuery("select a from jpaAuthor a where id=" + id);
54 return (Author)query.getSingleResult();
55 }
56
57
58
59
60 public Author update(Author author) {
61 Author dbAuthor = em.find(Author.class, author.getId());
62 dbAuthor.setFirstName(author.getFirstName());
63 dbAuthor.setLastName(author.getLastName());
64 dbAuthor.setSubject(author.getSubject());
65 dbAuthor.setPublishDate(author.getPublishDate());
66 return dbAuthor;
67 }
68
69
70
71
72 public Author updateByMerge(Author author) {
73 return em.merge(author);
74 }
75
76
77
78
79 public void remove(Author author) {
80 em.remove(author);
81 }
82 }