View Javadoc
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   * This class implements a DAO using javax.persistence.EntityManager. Most
14   * of the work of mapping the objects to the database is being performed in
15   * either the @Entity class or in a orm.xml descriptor file. The caller of 
16   * this object must manage the transaction scope. The EntityManager is being
17   * injected into the DAO at the start of the overall transaction.
18   * 
19   * @author jcstaff
20   * $Id:$
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       * This methos is not in the DAO interface and must be injected at a 
29       * point where we know the DAO's implementation class.
30       */
31      public void setEntityManager(EntityManager em) {
32          this.em=em;
33      }
34      
35      /* (non-Javadoc)
36       * @see ejava.examples.dao.jpa.AuthorDAO#create(ejava.examples.dao.domain.Author)
37       */
38      public void create(Author author) {
39          em.persist(author);
40      }
41      
42      /* (non-Javadoc)
43       * @see ejava.examples.dao.jpa.AuthorDAO#get(long)
44       */
45      public Author get(long id) {
46          return em.find(Author.class, id);
47      }
48      
49      /* (non-Javadoc)
50       * @see ejava.examples.dao.jpa.AuthorDAO#getByQuery(long)
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      /* (non-Javadoc)
58       * @see ejava.examples.dao.jpa.AuthorDAO#update(ejava.examples.dao.domain.Author)
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      /* (non-Javadoc)
70       * @see ejava.examples.dao.jpa.AuthorDAO#updateByMerge(ejava.examples.dao.domain.Author)
71       */
72      public Author updateByMerge(Author author) {
73          return em.merge(author);
74      }
75      
76      /* (non-Javadoc)
77       * @see ejava.examples.dao.jpa.AuthorDAO#remove(ejava.examples.dao.domain.Author)
78       */
79      public void remove(Author author) {
80          em.remove(author);
81      }
82  }