import java.sql.*; import java.util.*; import java.io.*; /* * ContactInfo * * $Author: $ * $Date: $ * $Revisions: $ * $Source: $ * To create a new ContactInfo * * ContactInfo instance = new ContactInfo * .. call the set methods // Set the fields as needed * String key = instance.store(); // .store() inserts record to database * // DB sequence "contact_info_seq" is used to get * // next primary key * * To get a ContactInfo from the database * // To retrieve a ContactInfo from database * ContactInfo instance = new ContactInfo("1234"); // pass the primary key to constructor * ... call the get() methods // and then call the getter methods * * * To update an existing ContactInfo * // To update an existing OrderObj * ContactInfo instance = new ContactInfo("1234"); // get it from database, call the setter methods * .. call the set methods // and then call store() * instance.store(); * * */ public class ContactInfo { private long key = 0; private String homePhone = ""; private String workPhone = ""; private String emailAddress = ""; private GregorianCalendar created = null; private GregorianCalendar updated = null; private boolean isDirty = false; /** * * To get an existing ContactInfo call constructor with primary key * */ public ContactInfo(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("ContactInfo(key) constructor, Exception: " + exp.getMessage()); } } /** * * To populate a ContactInfo where the sql select was done earlier by another object * call this constructor with the result set. * */ public ContactInfo(ResultSet rset) { applyResultSet(rset); //Populate this object with values from db } /*** * To create a new ContactInfo call no args constructor * then call the "set()" methods, and finally "store()" */ public ContactInfo() { } /** * * 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("ContactInfo.store(), Starting transaction"); returnKey = store(conn); conn.commit(); log("ContactInfo.store(), No Exceptions Committing"); } catch (Exception exp) { //Any exception thrown by store causes a rollback. log("ContactInfo.store(), Exception: " + exp.getMessage()); try { log("ContactInfo.store(), Failed: RollingBack"); conn.rollback(); } catch (SQLException rollbackExp) { log("ContactInfo.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("ContactInfo.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 ContactInfo 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" + " contact_info.contact_info_id as contact_info_contact_info_id, \n" + " contact_info.home_phone as contact_info_home_phone, \n" + " contact_info.work_phone as contact_info_work_phone, \n" + " contact_info.email_address as contact_info_email_address, \n" + " contact_info.created as contact_info_created, \n" + " contact_info.updated as contact_info_updated \n" + " from contact_info contact_info \n" + " where contact_info.contact_info_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("contact_info_contact_info_id"); homePhone = rset.getString("contact_info_home_phone"); workPhone = rset.getString("contact_info_work_phone"); emailAddress = rset.getString("contact_info_email_address"); if ( rset.getTimestamp("contact_info_created") != null) { gc = new GregorianCalendar(timezone); gc.setTime(new java.util.Date( rset.getTimestamp("contact_info_created").getTime())); created = gc; } if ( rset.getTimestamp("contact_info_updated") != null) { gc = new GregorianCalendar(timezone); gc.setTime(new java.util.Date( rset.getTimestamp("contact_info_updated").getTime())); updated = gc; } isDirty = false; } catch (Exception exp) { log("ContactInfo.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 contact_info_seq.nextval from dual \n"; stmt = conn.createStatement(); rset = stmt.executeQuery(sqlStmt); rset.next(); newKey = rset.getLong(1); log("newKey=" + newKey); sqlStmt = "insert into contact_info " + " ( " + " contact_info_id, \n" + " home_phone, \n" + " work_phone, \n" + " email_address, \n" + " created, \n" + " updated \n" + " ) " + " values ( ?, ?, ?, ?, sysdate, sysdate )"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,newKey); pStmt.setString(2,homePhone); pStmt.setString(3,workPhone); pStmt.setString(4,emailAddress); 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 contact_info " + " set " + " home_phone = ?, \n" + " work_phone = ?, \n" + " email_address = ?, \n" + " updated = sysdate \n" + " where contact_info_id = '" + key + "'"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setString(1,homePhone); pStmt.setString(2,workPhone); pStmt.setString(3,emailAddress); int rowsUpdated = pStmt.executeUpdate(); if ( rowsUpdated != 1) { log("Error: .insertToDB failed no rows inserted"); } pStmt.close(); isDirty = false; } /** * * Delete an ContactInfo * 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("ContactInfo.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("ContactInfo.delete(), Exception: " + closeExp.getMessage()); } } } /** * * */ public void delete(Connection conn) throws Exception { String sqlStmt = "delete from contact_info " + "where contact_info_id = ?"; PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,key); int rowsDeleted = pStmt.executeUpdate(); log(" Deleted row from contact_info where primary key was " + key); if ( rowsDeleted != 1) { log("Error: ContactInfo.delete failed no rows deleted"); } } public long getKey() { return key; } public String getHomePhone() { return homePhone; } public String getWorkPhone() { return workPhone; } public String getEmailAddress() { return emailAddress; } public GregorianCalendar getCreated() { return created; } public GregorianCalendar getUpdated() { return updated; } public void setHomePhone(String in) { homePhone = in; isDirty = true; } public void setWorkPhone(String in) { workPhone = in; isDirty = true; } public void setEmailAddress(String in) { emailAddress = 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[] ) { ContactInfo object = new ContactInfo(1); System.out.println("homePhone = " + object.homePhone ); System.out.println("workPhone = " + object.workPhone ); System.out.println("emailAddress = " + object.emailAddress ); System.out.println("created = " + object.created ); System.out.println("updated = " + object.updated ); } }