import java.sql.*; import java.util.*; import java.io.*; /* * Region * * $Author: $ * $Date: $ * $Revisions: $ * $Source: $ * To create a new Region * * Region instance = new Region * .. call the set methods // Set the fields as needed * String key = instance.store(); // .store() inserts record to database * // DB sequence "region_seq" is used to get * // next primary key * * To get a Region from the database * // To retrieve a Region from database * Region instance = new Region("1234"); // pass the primary key to constructor * ... call the get() methods // and then call the getter methods * * * To update an existing Region * // To update an existing OrderObj * Region instance = new Region("1234"); // get it from database, call the setter methods * .. call the set methods // and then call store() * instance.store(); * * */ public class Region { private long key = 0; private String regionName = ""; private long divisionId = 0; private boolean isDirty = false; /** * * To get an existing Region call constructor with primary key * */ public Region(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("Region(key) constructor, Exception: " + exp.getMessage()); } } /** * * To populate a Region where the sql select was done earlier by another object * call this constructor with the result set. * */ public Region(ResultSet rset) { applyResultSet(rset); //Populate this object with values from db } /*** * To create a new Region call no args constructor * then call the "set()" methods, and finally "store()" */ public Region() { } /** * * 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("Region.store(), Starting transaction"); returnKey = store(conn); conn.commit(); log("Region.store(), No Exceptions Committing"); } catch (Exception exp) { //Any exception thrown by store causes a rollback. log("Region.store(), Exception: " + exp.getMessage()); try { log("Region.store(), Failed: RollingBack"); conn.rollback(); } catch (SQLException rollbackExp) { log("Region.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("Region.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 Region 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" + " region.region_id as region_region_id, \n" + " region.name as region_name, \n" + " region.division_id as region_division_id \n" + " from region region \n" + " where region.region_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("region_region_id"); regionName = rset.getString("region_name"); divisionId = rset.getLong("region_division_id"); isDirty = false; } catch (Exception exp) { log("Region.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 region_seq.nextval from dual \n"; stmt = conn.createStatement(); rset = stmt.executeQuery(sqlStmt); rset.next(); newKey = rset.getLong(1); log("newKey=" + newKey); sqlStmt = "insert into region " + " ( " + " region_id, \n" + " name, \n" + " division_id \n" + " ) " + " values ( ?, ?, ? )"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,newKey); pStmt.setString(2,regionName); pStmt.setLong(3,divisionId); 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 region " + " set " + " name = ?, \n" + " division_id = ? \n" + " where region_id = '" + key + "'"; log("Sql stmt=" + sqlStmt); PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setString(1,regionName); pStmt.setLong(2,divisionId); int rowsUpdated = pStmt.executeUpdate(); if ( rowsUpdated != 1) { log("Error: .insertToDB failed no rows inserted"); } pStmt.close(); isDirty = false; } /** * * Delete an Region * 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("Region.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("Region.delete(), Exception: " + closeExp.getMessage()); } } } /** * * */ public void delete(Connection conn) throws Exception { String sqlStmt = "delete from region " + "where region_id = ?"; PreparedStatement pStmt = conn.prepareStatement(sqlStmt); pStmt.setLong(1,key); int rowsDeleted = pStmt.executeUpdate(); log(" Deleted row from region where primary key was " + key); if ( rowsDeleted != 1) { log("Error: Region.delete failed no rows deleted"); } } public long getKey() { return key; } public String getRegionName() { return regionName; } public long getDivisionId() { return divisionId; } public void setRegionName(String in) { regionName = in; isDirty = true; } public void setDivisionId(long in) { divisionId = 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[] ) { Region object = new Region(1); System.out.println("regionName = " + object.regionName ); System.out.println("divisionId = " + object.divisionId ); } }