1 package ejava.examples.daoex.dao;
2
3 import java.lang.reflect.Field;
4 import java.sql.Connection;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.util.List;
9
10 import javax.persistence.PersistenceException;
11
12 import ejava.examples.daoex.bo.Book;
13
14 public class JDBCBookDAOImpl implements BookDAO {
15 private Connection connection;
16
17 public void setConnection(Connection connection) {
18 this.connection = connection;
19 }
20
21 @Override
22 public Book create(Book book) throws PersistenceException {
23 PreparedStatement statement=null;
24 ResultSet rs = null;
25 try {
26 statement=connection.prepareStatement(
27 "insert into JPADAO_BOOK (ID, DESCRIPTION, PAGES, TITLE) " +
28 "values (null, ?, ?, ?)");
29 statement.setString(1, book.getDescription());
30 statement.setInt(2, book.getPages());
31 statement.setString(3, book.getTitle());
32 statement.execute();
33 statement.close();
34
35 Field id = Book.class.getDeclaredField("id");
36 id.setAccessible(true);
37 statement = connection.prepareStatement("call identity()");
38 rs = statement.executeQuery();
39 if (rs.next()) {
40 id.set(book, rs.getLong(1));
41 }
42
43 return book;
44 } catch (SQLException ex) {
45 throw new PersistenceException("SQL error creating book", ex);
46 } catch (NoSuchFieldException ex) {
47 throw new RuntimeException("Error locating id field", ex);
48 } catch (SecurityException ex) {
49 throw new RuntimeException("Security error setting id", ex);
50 } catch (IllegalArgumentException ex) {
51 throw new RuntimeException("Error setting id", ex);
52 } catch (IllegalAccessException ex) {
53 throw new RuntimeException("Access error setting id", ex);
54 } finally {
55 try { rs.close(); } catch (Exception ex){}
56 try { statement.close(); } catch (Exception ex){}
57 }
58 }
59
60 @Override
61 public Book update(Book book) throws PersistenceException {
62
63 return null;
64 }
65
66 @Override
67 public Book get(long id) throws PersistenceException {
68
69 return null;
70 }
71
72 @Override
73 public void remove(Book book) throws PersistenceException {
74
75
76 }
77
78 @Override
79 public List<Book> findAll(int start, int count) throws PersistenceException {
80
81 return null;
82 }
83
84 }