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