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.bo.VehicleRegistration;
16 import ejava.projects.edmv.dao.DAOException;
17 import ejava.projects.edmv.dao.VehicleDAO;
18
19
20
21
22
23
24 public class JDBCVehicleDAO implements VehicleDAO {
25 private static Logger log = LoggerFactory.getLogger(JDBCVehicleDAO.class);
26 private Connection connection;
27
28 public void setConnection(Connection connection) {
29 this.connection = connection;
30 }
31
32 public void createRegistration(VehicleRegistration registration)
33 throws DAOException {
34 PreparedStatement statement1 = null;
35 Statement statement2 = null;
36 PreparedStatement statement3 = null;
37
38 try {
39 statement1 = connection.prepareStatement(
40 "INSERT INTO EDMV_VREG " +
41 "(ID, VIN) " +
42 "VALUES (null, ?)");
43 statement1.setString(1, registration.getVin());
44 statement1.execute();
45
46 ResultSet rs = null;
47 try {
48 Method setId = VehicleRegistration.class.getDeclaredMethod(
49 "setId", new Class[]{long.class});
50 setId.setAccessible(true);
51
52
53 statement2 = connection.createStatement();
54 rs = statement2.executeQuery("call identity()");
55 if (rs.next()) {
56 long id = rs.getLong(1);
57 setId.invoke(registration, id);
58 }
59 }
60 catch (Exception ex) {
61 log.error("SQL error getting registration id:" + ex, ex);
62 throw new DAOException("error getting registration id:"+ex, ex);
63 } finally {
64 try { rs.close(); } catch (Exception ignored) {}
65 }
66
67 for (Person owner : registration.getOwners()) {
68 if (owner.getId() == 0) {
69 throw new DAOException("transient Vehicle Owner found");
70 }
71 statement3 = connection.prepareStatement(
72 "INSERT INTO EDMV_VREG_OWNER_LINK " +
73 "(VEHICLE_ID, OWNER_ID) " +
74 "VALUES (?, ?)");
75 statement3.setLong(1, registration.getId());
76 statement3.setLong(2, owner.getId());
77 statement3.execute();
78 }
79 }
80 catch (SQLException ex) {
81 log.error("SQL error creating registration:" + ex, ex);
82 throw new DAOException("error creating registration:"+ex, ex);
83 }
84 finally {
85 try { statement1.close(); } catch (Exception ignored) {}
86 try { statement2.close(); } catch (Exception ignored) {}
87 try { statement3.close(); } catch (Exception ignored) {}
88 }
89 }
90
91 public List<VehicleRegistration> getRegistrations(int index, int count)
92 throws DAOException {
93 throw new DAOException("not implemented");
94 }
95 }