import java.sql.*; import java.util.*; import java.io.*; /* * Car * * $Author: $ * $Date: $ * $Revisions: $ * $Source: $ * To create a new Car * * Car instance = new Car * .. call the set methods // Set the fields as needed * String key = instance.store(); // .store() inserts record to database * // DB sequence "car_seq" is used to get * // next primary key * * To get a Car from the database * // To retrieve a Car from database * Car instance = new Car("1234"); // pass the primary key to constructor * ... call the get() methods // and then call the getter methods * * * To update an existing Car * // To update an existing OrderObj * Car instance = new Car("1234"); // get it from database, call the setter methods * .. call the set methods // and then call store() * instance.store(); * * */ public class Car { private long key = 0; private long driverId = 0; private String make = ""; private String model = ""; private String year = ""; private int mileage = 0; private GregorianCalendar created = null; private GregorianCalendar updated = null; private boolean isDirty = false; /** * * To get an existing Car call constructor with primary key * */ public Car(long keyIn) { Connection conn = null; Statement stmt = null; try { conn = getConnection(); stmt = conn.createStatement(); } catch (SQLException exp) { log("Driver(key) constructor, Exception: " + exp.getMessage()); } key = keyIn; ResultSet rset = doSelect(conn, stmt); try { rset.close(); stmt.close(); conn.close(); } catch (SQLException exp) { log("Car(key) constructor, Exception: " + exp.getMessage()); } } /** * * To populate a Car where the sql select was done earlier by another object * call this constructor with the result set. * */ public Car(ResultSet rset) { applyResultSet(rset); //Populate this object with values from db } /*** * To create a new Car call no args constructor * then call the "set()" methods, and finally "store()" */ public Car() { } /** * * Persist our properties to the db. Also call store() on any dependent objects. * If no Connection was passed in then we are responisible for beginning the transaction * Turn off auto commit, and rollback if we get exception from this or any dependent objects * */ public long store() throws Exception { long returnKey = key; Connection conn = getConnection(); try { conn.setAutoCommit(false); log("Car.store(), Starting transaction"); returnKey = store(conn); conn.commit(); log("Car.store(), No Exceptions Committing"); } catch (Exception exp) { //Any exception thrown by store causes a rollback. log("Car.store(), Exception: " + exp.getMessage()); try { log("Car.store(), Failed: RollingBack"); conn.rollback(); } catch (SQLException rollbackExp) { log("Car.store(), Exception: " + rollbackExp.getMessage()); } throw exp; //Throw exception back up so that user interface can report error } finally { try { conn.close(); } catch (SQLException closeExp) { log("Car.store(), Exception: " + closeExp.getMessage()); } } return returnKey; } /** * * Persist our properties to the db. Also call store() on any dependent objects. * If a Connection was passed in then a object higher up is handling the transactions * for us. Throw on any exceptions so that the higher object can catch them and rollback. * This method will do an insert for new Car and a update for existing ones * */ public long store(Connection conn) throws Exception { long returnKey = key; if ( key == 0 ) { returnKey = insertToDB(conn); } else { if ( isDirty ) { updateOnDB(conn); } } return returnKey; } /** * */ private ResultSet doSelect(Connection conn, Statement stmt) { ResultSet rset = null; try { String sqlStmt = "select \n" + " car.car_id as car_car_id, \n" + " car.driver_id as car_driver_id, \n" + " car.make as car_make, \n" + " car.model as car_model, \n" + " car.year as car_year, \n" + " car.mileage as car_mileage, \n" + " car.created as car_created, \n" + " car.updated as car_updated \n" + " from car car \n" + " where car.car_id = " + key ; log("sqlStmt=" + sqlStmt); rset = stmt.executeQuery(sqlStmt); rset.next(); applyResultSet(rset); } catch (Exception exp) { log(".doSelect(), SQLException: " + exp.getMessage()); } return rset; } /** * */ private void applyResultSet(ResultSet rset) { TimeZone timezone = TimeZone.getDefault(); GregorianCalendar gc = null; java.sql.Clob textClob = null; InputStream in = null; int b = 0; StringBuffer stringBuffer = null; try { key = rset.getLong("car_car_id"); driverId = rset.getLong("car_driver_id"); make = rset.getString("car_make"); model = rset.getString("car_model"); year = rset.getString("car_year"); mileage = rset.getInt("car_mileage"); if ( rset.getTimestamp("car_created") != null) { gc = new GregorianCalendar(timezone); gc.setTime(new java.util.Date( rset.getTimestamp("car_created").getTime())); created = gc; } if ( rset.getTimestamp("car_updated") != null) { gc = new GregorianCalendar(timezone); gc.setTime(new java.util.Date( rset.getTimestamp("car_updated").getTime())); updated = gc; } isDirty = false; } catch (Exception exp) { log("Car.applyResultSet(): SQLException:" + exp.getMessage()); } } /** * */ private long insertToDB(Connection conn) throws Exception { long newKey = 0; String sqlStmt = ""; ByteArrayInputStream bs = null; InputStream in = null; Statement stmt = null; ResultSet rset = null; sqlStmt = "select car_seq.nextval from dual \n"; stmt = conn.createStatement(); rset = stmt.executeQuery(sqlStmt); rset.next(); newKey = rset.getLong(1); log("newKey=" + newKey); sqlStmt = "insert into car " + " ( " + " car_id, \n" + " driver_id, \n" + " make, \n" + " model, \n" + " year, \n" + " mileage, \n" + " created, \n" + " updated \n" + " ) " + " values ( ?, ?, ?, ?, ?, ?, sysdate, sysdate )"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,newKey); pStmt.setLong(2,driverId ); pStmt.setString(3,make); pStmt.setString(4,model); pStmt.setString(5,year); pStmt.setInt(6,mileage); int rowsInserted = pStmt.executeUpdate(); log(" rows inserted =" + rowsInserted); if ( rowsInserted != 1) { log("Error: .insertToDB failed no rows inserted"); } pStmt.close(); isDirty = false; return newKey; } /** * */ private void updateOnDB(Connection conn) throws Exception { ByteArrayInputStream bs = null; InputStream in = null; String sqlStmt = "update car " + " set " + " driver_id = ?, \n" + " make = ?, \n" + " model = ?, \n" + " year = ?, \n" + " mileage = ?, \n" + " updated = sysdate \n" + " where car_id = '" + key + "'"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,driverId ); pStmt.setString(2,make); pStmt.setString(3,model); pStmt.setString(4,year); pStmt.setInt(5,mileage); int rowsUpdated = pStmt.executeUpdate(); if ( rowsUpdated != 1) { log("Error: .insertToDB failed no rows inserted"); } pStmt.close(); isDirty = false; } /** * * Delete an Car * Also call delete() on any dependent objects. * If no Connection was passed in then we are responisible for beginning the transaction * Turn off auto commit, and rollback if we get exception from this or any dependent objects * */ public void delete() throws Exception { long returnKey = key; Connection conn = getConnection(); try { conn.setAutoCommit(false); delete(conn); conn.commit(); } catch (Exception exp) { //Any exception thrown by store causes a rollback. log("Car.delete(), Exception: " + exp.getMessage()); try { conn.rollback(); } catch (SQLException rollbackExp) { log(".delete(), Exception: " + rollbackExp.getMessage()); } throw exp; //Throw exception back up so that user interface can report error } finally { try { conn.close(); } catch (SQLException closeExp) { log("Car.delete(), Exception: " + closeExp.getMessage()); } } } /** * * */ public void delete(Connection conn) throws Exception { String sqlStmt = "delete from car " + "where car_id = ?"; PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,key); int rowsDeleted = pStmt.executeUpdate(); log(" Deleted row from car where primary key was " + key); if ( rowsDeleted != 1) { log("Error: Car.delete failed no rows deleted"); } } public long getKey() { return key; } public long getDriverId () { return driverId ; } public String getMake() { return make; } public String getModel() { return model; } public String getYear() { return year; } public int getMileage() { return mileage; } public GregorianCalendar getCreated() { return created; } public GregorianCalendar getUpdated() { return updated; } public void setDriverId (long in) { driverId = in; isDirty = true; } public void setMake(String in) { make = in; isDirty = true; } public void setModel(String in) { model = in; isDirty = true; } public void setYear(String in) { year = in; isDirty = true; } public void setMileage(int in) { mileage = in; isDirty = true; } public void setCreated(GregorianCalendar in) { created = in; isDirty = true; } public void setUpdated(GregorianCalendar in) { updated = in; isDirty = true; } /** * Write to Log */ private void log(String messageIn) { System.out.println(messageIn); } /** * Get JDBC Connection to the DataBase * Note: this should be returning connections from a pool. */ private Connection getConnection() { Connection conn = null; String dbServer = "@myserver.mycompnay.com"; String dbPort = "1526"; String dbSid = "mysid"; String dbUserId = "username"; String dbPassword = "password"; try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); String connectString = "jdbc:oracle:thin:" + dbServer + ":" + dbPort + ":" + dbSid; conn = DriverManager.getConnection (connectString, dbUserId, dbPassword); } catch (SQLException exp) { log("Exception: " + exp.getMessage() ); } return conn; } /** * A main method for testing */ public static void main(String args[] ) { Car object = new Car(1); System.out.println("driverId = " + object.driverId ); System.out.println("make = " + object.make ); System.out.println("model = " + object.model ); System.out.println("year = " + object.year ); System.out.println("mileage = " + object.mileage ); System.out.println("created = " + object.created ); System.out.println("updated = " + object.updated ); } }