1 package ejava.projects.edmv.jdbc;
2
3 import java.lang.reflect.Method;
4 import java.sql.Connection;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.sql.Statement;
9 import java.util.List;
10
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13
14 import ejava.projects.edmv.bo.Person;
15 import ejava.projects.edmv.dao.DAOException;
16 import ejava.projects.edmv.dao.PersonDAO;
17
18
19
20
21
22
23 public class JDBCPersonDAO implements PersonDAO {
24 private static Logger log = LoggerFactory.getLogger(JDBCPersonDAO.class);
25 private Connection connection;
26
27 public void setConnection(Connection connection) {
28 this.connection = connection;
29 }
30
31 public void createPerson(Person person)
32 throws DAOException {
33 PreparedStatement statement1 = null;
34 Statement statement2 = null;
35 ResultSet rs = null;
36
37 try {
38 statement1 = connection.prepareStatement(
39 "INSERT INTO EDMV_PERSON " +
40 "(ID, LAST_NAME) " +
41 "VALUES (null, ?)");
42 statement1.setString(1, person.getLastName());
43 statement1.execute();
44
45 Method setId = Person.class.getDeclaredMethod(
46 "setId", new Class[]{long.class});
47 setId.setAccessible(true);
48
49
50 statement2 = connection.createStatement();
51 rs = statement2.executeQuery("call identity()");
52 if (rs.next()) {
53 long id = rs.getLong(1);
54 setId.invoke(person, id);
55 }
56 }
57 catch (SQLException ex) {
58 log.error("SQL error creating person", ex);
59 throw new DAOException("error creating person:"+ex, ex);
60 }
61 catch (Exception ex) {
62 log.error("error creating person", ex);
63 throw new DAOException("error creating person:"+ex, ex);
64 }
65 finally {
66 try { rs.close(); } catch (Exception ignored) {}
67 try { statement1.close(); } catch (Exception ignored) {}
68 try { statement2.close(); } catch (Exception ignored) {}
69 }
70 }
71
72 public Person getPerson(long id)
73 throws DAOException {
74 throw new DAOException("not implemented");
75 }
76
77 public List<Person> getPeople(int index, int count)
78 throws DAOException {
79 throw new DAOException("not implemented");
80 }
81 }