import java.sql.*; import java.util.*; import java.io.*; /* * Address * * $Author: $ * $Date: $ * $Revisions: $ * $Source: $ * To create a new Address * * Address instance = new Address * .. call the set methods // Set the fields as needed * String key = instance.store(); // .store() inserts record to database * // DB sequence "driver_address_seq" is used to get * // next primary key * * To get a Address from the database * // To retrieve a Address from database * Address instance = new Address("1234"); // pass the primary key to constructor * ... call the get() methods // and then call the getter methods * * * To update an existing Address * // To update an existing OrderObj * Address instance = new Address("1234"); // get it from database, call the setter methods * .. call the set methods // and then call store() * instance.store(); * * */ public class Address { private long key = 0; private String addressLine1 = ""; private String addressLine2 = ""; private String city = ""; private String state = ""; private String zip = ""; private GregorianCalendar dateMovedIn = null; private GregorianCalendar created = null; private GregorianCalendar updated = null; private boolean isDirty = false; /** * * To get an existing Address call constructor with primary key * */ public Address(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("Address(key) constructor, Exception: " + exp.getMessage()); } } /** * * To populate a Address where the sql select was done earlier by another object * call this constructor with the result set. * */ public Address(ResultSet rset) { applyResultSet(rset); //Populate this object with values from db } /*** * To create a new Address call no args constructor * then call the "set()" methods, and finally "store()" */ public Address() { } /** * * 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("Address.store(), Starting transaction"); returnKey = store(conn); conn.commit(); log("Address.store(), No Exceptions Committing"); } catch (Exception exp) { //Any exception thrown by store causes a rollback. log("Address.store(), Exception: " + exp.getMessage()); try { log("Address.store(), Failed: RollingBack"); conn.rollback(); } catch (SQLException rollbackExp) { log("Address.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("Address.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 Address 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" + " driver_address.address_id as driver_address_address_id, \n" + " driver_address.address_line1 as driver_address_address_line1, \n" + " driver_address.address_line2 as driver_address_address_line2, \n" + " driver_address.city as driver_address_city, \n" + " driver_address.state as driver_address_state, \n" + " driver_address.zip as driver_address_zip, \n" + " driver_address.date_moved_in as driver_address_date_moved_in, \n" + " driver_address.created as driver_address_created, \n" + " driver_address.updated as driver_address_updated \n" + " from driver_address driver_address \n" + " where driver_address.address_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("driver_address_address_id"); addressLine1 = rset.getString("driver_address_address_line1"); addressLine2 = rset.getString("driver_address_address_line2"); city = rset.getString("driver_address_city"); state = rset.getString("driver_address_state"); zip = rset.getString("driver_address_zip"); if ( rset.getTimestamp("driver_address_date_moved_in") != null) { gc = new GregorianCalendar(timezone); gc.setTime(new java.util.Date( rset.getTimestamp("driver_address_date_moved_in").getTime())); dateMovedIn = gc; } if ( rset.getTimestamp("driver_address_created") != null) { gc = new GregorianCalendar(timezone); gc.setTime(new java.util.Date( rset.getTimestamp("driver_address_created").getTime())); created = gc; } if ( rset.getTimestamp("driver_address_updated") != null) { gc = new GregorianCalendar(timezone); gc.setTime(new java.util.Date( rset.getTimestamp("driver_address_updated").getTime())); updated = gc; } isDirty = false; } catch (Exception exp) { log("Address.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 driver_address_seq.nextval from dual \n"; stmt = conn.createStatement(); rset = stmt.executeQuery(sqlStmt); rset.next(); newKey = rset.getLong(1); log("newKey=" + newKey); sqlStmt = "insert into driver_address " + " ( " + " address_id, \n" + " address_line1, \n" + " address_line2, \n" + " city, \n" + " state, \n" + " zip, \n" + " date_moved_in, \n" + " created, \n" + " updated \n" + " ) " + " values ( ?, ?, ?, ?, ?, ?, ?, sysdate, sysdate )"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,newKey); pStmt.setString(2,addressLine1); pStmt.setString(3,addressLine2); pStmt.setString(4,city); pStmt.setString(5,state); pStmt.setString(6,zip); if ( dateMovedIn != null) { pStmt.setTimestamp(7, new java.sql.Timestamp(dateMovedIn.getTime().getTime() ) ); } else { pStmt.setNull(7, java.sql.Types.DATE); } 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 driver_address " + " set " + " address_line1 = ?, \n" + " address_line2 = ?, \n" + " city = ?, \n" + " state = ?, \n" + " zip = ?, \n" + " date_moved_in = ?, \n" + " updated = sysdate \n" + " where address_id = '" + key + "'"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setString(1,addressLine1); pStmt.setString(2,addressLine2); pStmt.setString(3,city); pStmt.setString(4,state); pStmt.setString(5,zip); if ( dateMovedIn != null) { pStmt.setTimestamp(6, new java.sql.Timestamp(dateMovedIn.getTime().getTime() ) ); } else { pStmt.setNull(6, java.sql.Types.DATE); } int rowsUpdated = pStmt.executeUpdate(); if ( rowsUpdated != 1) { log("Error: .insertToDB failed no rows inserted"); } pStmt.close(); isDirty = false; } /** * * Delete an Address * 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("Address.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("Address.delete(), Exception: " + closeExp.getMessage()); } } } /** * * */ public void delete(Connection conn) throws Exception { String sqlStmt = "delete from driver_address " + "where address_id = ?"; PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,key); int rowsDeleted = pStmt.executeUpdate(); log(" Deleted row from driver_address where primary key was " + key); if ( rowsDeleted != 1) { log("Error: Address.delete failed no rows deleted"); } } public long getKey() { return key; } public String getAddressLine1() { return addressLine1; } public String getAddressLine2() { return addressLine2; } public String getCity() { return city; } public String getState() { return state; } public String getZip() { return zip; } public GregorianCalendar getDateMovedIn() { return dateMovedIn; } public GregorianCalendar getCreated() { return created; } public GregorianCalendar getUpdated() { return updated; } public void setAddressLine1(String in) { addressLine1 = in; isDirty = true; } public void setAddressLine2(String in) { addressLine2 = in; isDirty = true; } public void setCity(String in) { city = in; isDirty = true; } public void setState(String in) { state = in; isDirty = true; } public void setZip(String in) { zip = in; isDirty = true; } public void setDateMovedIn(GregorianCalendar in) { dateMovedIn = 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[] ) { Address object = new Address(1); System.out.println("addressLine1 = " + object.addressLine1 ); System.out.println("addressLine2 = " + object.addressLine2 ); System.out.println("city = " + object.city ); System.out.println("state = " + object.state ); System.out.println("zip = " + object.zip ); System.out.println("dateMovedIn = " + object.dateMovedIn ); System.out.println("created = " + object.created ); System.out.println("updated = " + object.updated ); } }