1 package ejava.examples.daoex.dao;
2
3 import java.lang.reflect.Field;
4 import java.util.List;
5
6 import javax.persistence.EntityManager;
7 import javax.persistence.PersistenceException;
8
9 import ejava.examples.daoex.bo.Book;
10
11 public class JPANativeSQLBookDAO implements BookDAO {
12 private EntityManager em;
13
14 public void setEntityManager(EntityManager em) {
15 this.em = em;
16 }
17
18 @Override
19 public Book create(Book book) throws PersistenceException {
20 em.createNativeQuery(
21 "insert into JPADAO_BOOK (ID, DESCRIPTION, PAGES, TITLE) " +
22 "values (null, ?1, ?2, ?3)")
23 .setParameter(1, book.getDescription())
24 .setParameter(2, book.getPages())
25 .setParameter(3, book.getTitle())
26 .executeUpdate();
27
28 int idVal = ((Number)em.createNativeQuery("call identity()")
29 .getSingleResult()).intValue();
30 try {
31 Field id = Book.class.getDeclaredField("id");
32 id.setAccessible(true);
33 id.set(book, idVal);
34 } catch (Exception ex) {
35 throw new RuntimeException("Error setting id", ex);
36 }
37
38 return book;
39 }
40
41 @Override
42 public Book update(Book book) throws PersistenceException {
43
44 return null;
45 }
46
47 @Override
48 public Book get(long id) throws PersistenceException {
49
50 return null;
51 }
52
53 @Override
54 public void remove(Book book) throws PersistenceException {
55
56
57 }
58
59 @Override
60 public List<Book> findAll(int start, int count) throws PersistenceException {
61
62 return null;
63 }
64
65 }