/*
* @author Elango
* @version 1.2
*
* Development Environment : Oracle9i JDeveloper
* Name of the Application : InheritanceSample.java
* Creation/Modification History :
*
* Elango 21-Aug-2001 Created
* Venky 09-Oct-2001 Modified for SQLJ implementation
* Stephen 2-Apr-2003 Certified on Linux
*
*/

package oracle.otnsamples.sqlj.inheritance;
// import for JDBC classes
import java.sql.Connection;
import java.sql.SQLException;
import java.math.BigDecimal;
//import sqlj related classes
import oracle.sqlj.runtime.Oracle;
/**
* Sample scenario
* Consider a Residential University where the major players are
* Students,Teachers and Parttime Students. This model has a Person object
* which is the super type with attributes which are common to all persons such
* as SSN, Name, Dateofbirth, sex and Address. It has two sub-types, a Teacher and
* a Student. Teacher has addtional attributes like courses taught,salary and
* date of joining. Student has courses taken, grade and year of completion.
* A Parttime student is a sub-type of student with some additional attributes
* such as No of hours, Start time and Batch code. All the sub-types have
* overriden methods for setting and retrieving the attributes.
*
* This sample illustrates
*
* 1. Overloading Methods :- Here the method getPersonDetails() is
* overloaded. When invoked on Student Object, this method returns
* the courses taken, grade etc information apart from Name, Address
* information. When invoked on Teacher Object, this method returns the
* information like courses taught, Salary, Dept apart from Name, Address.
*
* 2. Dynamic Method Dispatch :- This is nothing but run-time polymorphism.
* When you invoke a overriden method, the implementation of the methods is
* searched , beginning from the current object , the method is searched
* upwards ( the type and then , all the super types of type).
* In other words, if setAddress() in invoked from a Student Object, then
* method in Person Object is invoked ,since there is no implementation of
* setAddress() in Student Object but if the same method is called from
* a Teacher object the implementation in the Teacher Object is called.
*
* 3. Substituting Types in a Type Hierarchy :- A base object type can hold
* any of its sub-types objects (i.e) Person is the base type and it can
* hold either a Student , Teacher or a parttimestudent object which are
* sub-types of Person.
*
* In this sample the user can View/Edit person details.
*
* For viewing person details, the overrided getPersonDetails() method is
* called which returns a String representation of the Object attributes.
*
* For editing person details, the overrided setPersonDetails() method is
* called, which sets the attributes and calls the setAddress() method for
* setting the address.
*
* The gui part of this sample is handled separately in PersonFrame.java
*/
public class InheritanceSample {
private PersonFrame gui; // Handle gui
private Connection conn;
/**
* Constructor. Initializes the frame
*/
public InheritanceSample() {
try {
gui = new PersonFrame(this);
} catch(Exception ex) {
gui.putStatus(" Error : Couldn't Initialize frame , "+ex.toString());
}
}
/**
* Main entry point for the class. Creates an object and calls the dbConnect()
* method to establish connection to database. Sets the map between the java
* classes and object types in the database.Invokes the displayPersonDetails()
* to retrieve SSN,Name and Object type of the Objects inside the
* PersonDetails table.
*/
public static void main(String args[]) {
// Create an object of the Sample
InheritanceSample inheritanceSample = new InheritanceSample();
// Connect to the database
inheritanceSample.dbConnect();
// Display SSN, Name and Object type from PersonDetails table
inheritanceSample.displayPersonDetails();
}
/**
* Connect to the database using the connection parameters specified in the
* Connection.properties file.
*/
void dbConnect() {
try{
gui.putStatus(" Connecting to Database ....");
Oracle.connect(this.getClass(), "../../../../Connection.properties");
gui.putStatus(" Connected to Database ...");
}catch(Exception ex){ // Trap errors
System.out.println("Error while Connecting to the database: "+
ex.toString());
System.exit(0);
}
}
/**
* Dispatches the gui events to the appropriate method, which performs
* the required SQLJ operations. This method is invoked when event occurs
* in the gui (like table Selection, Button clicks etc.). This method
* is invoked from the setupListeners section of PersonFrame.java
*/
public void dispatchEvent (String eventName) {
if (eventName.equals("GET PERSON DETAILS"))
// Displays the person details in ViewPersonDetailsFrame
selectPersonDetails();

if (eventName.equals("SHOW PERSON DETAILS"))
// Shows the person details in EditPersonDetailsFrame for editing
showPersonDetails();

if (eventName.equals("SET PERSON DETAILS"))
// Updates the person details to the table
setPersonDetails();
if (eventName.equals("EXIT"))
// performs clean up and closes the application
exitApplication();
}

/**
* This method retrieves the objects from the PersonDetails table and displays
* SSN, Name and Object type of objects in a JTable.
*/
private void displayPersonDetails() {
String ssnNo = null;
String fullName = null;
String objType = null;
Student st=new Student();
ParttimeStudent ps=new ParttimeStudent();
Teacher t=new Teacher();

// To hold the retrieved object
Person personObj=null;
#sql iterator objectIter (Person);
objectIter tempIter=null;

try {
#sql tempIter={SELECT P.PERSON FROM PERSONDETAILS P};
while(true){
#sql { FETCH :tempIter INTO :personObj};
if(tempIter.endFetch())break;
/* Retrieve the object and assign it to a person object, a person object
can hold all its sub-types objects (substitutability) */ /* An object of parttimestudent will also be an instance of student,
since parttimestudent is a sub-type of student. Hence the retrieved
object is first compared with a partimestudent and then with a
student(a student object will not be an instance of parttimestudent)
*/
// If the retrieved object is a parttimestudent
if(personObj instanceof ParttimeStudent)
objType=" P ";
// If the retrieved object is a student
else if(personObj instanceof Student)
objType=" S ";
// If the retrieved object is a teacher
else if(personObj instanceof Teacher)
objType=" T ";
// Some other sub-type of person
else objType=" O ";
// Get the SSN
ssnNo = personObj.getSsn();
// Get the full name
fullName = personObj.getFirstname() + " " + personObj.getLastname();
// Add a row in the person table
gui.addToJTable(ssnNo,fullName,objType);
}
gui.putStatus(" Select a person ...");
} catch(Exception ex) { // Trap errors
gui.putStatus("Error while Displaying : "+ex.toString());
} finally {
try {
tempIter.close();
} catch(SQLException sqe){
gui.putStatus("Error while Displaying : "+sqe.toString());
}
}
}
/**
* This method retrieves the person details and displays it in the
* ViewPersonDetailsFrame.java
*/
private void selectPersonDetails() {
// Call the getSelectedPerson() method to retrieve the Person object
// from the database
Person personObj = getSelectedPerson();
if(personObj != null) {
try {
// If the retrieved object is a parttimestudent
if(personObj instanceof ParttimeStudent) {
// Get the parttimestudent object
ParttimeStudent pstudent = (ParttimeStudent)personObj;

// call the getpersondetails() member function of the parttimestudent
// object ,it returns all the attributes of a parttime student object
gui.viewPerson.showParttime_studentDetails(
pstudent.getpersondetails());
}
// If the retrieved object is a student
else if(personObj instanceof Student) {
// Get the Student object
Student student = (Student)personObj;

//* call the getpersondetails() member function of the student
//object ,it returns all the attributes of a student object
gui.viewPerson.showStudentDetails(student.getpersondetails());
}
// If the retrieved object is a teacher
else if(personObj instanceof Teacher) {
// Get the teacher object
Teacher teacher = (Teacher)personObj;

// call the getpersondetails() member function of the teacher object,
//it returns all the attributes of a teacher
gui.viewPerson.showTeacherDetails(teacher.getpersondetails());
}
// hide the PersonFrame
gui.setVisible(false);
} catch(Exception ex) { // Trap errors
gui.putStatus("Error while Selecting: "+ex.toString());
}
}
}
/**
* This method retrieves the person object and displays the attributes in the
* EditPersonDetailsFrame for editing.
*/
private void showPersonDetails() {
// Call the getSelectedPerson() method to retrieve the Person object
// from the database
Person personObj = getSelectedPerson();
if(personObj != null)
// Display the person object
gui.editPerson.showPersonDetails(personObj);
}
/**
* Update the person details to the database
*/
private void setPersonDetails() {
// Update the edited fields to the Object
Person personObj = preparePerson();
try {
String ssn = personObj.getSsn();
#sql {UPDATE PERSONDETAILS P SET P.PERSON =:personObj WHERE
P.PERSON.ssn= :ssn };
#sql {COMMIT};
} catch(Exception ex) { // Trap errors
gui.putStatus("Error while updating person: "+ex.toString());
}
}

/**
* Update the attributes of the person object with the edited values
*/
private Person preparePerson() {
// Object of the EditPersonDetailsFrame
EditPersonDetailsFrame EditFrame = gui.editPerson;
// The person object that was edited
Person personObj = gui.personObj;
// if the person is a Parttimestudent
if(personObj instanceof ParttimeStudent) {
// Get the parttime student object
ParttimeStudent pstudent = (ParttimeStudent)personObj;
// Get the edited values
String Grade = EditFrame.txtGrade.getText();
String Yearofcompletion = EditFrame.txtYearofCompletion.getText();
String Coursestaken = EditFrame.txtCoursesTaken.getText();
BigDecimal Hours = new BigDecimal(EditFrame.txtHours.getText());
String Batchcode = EditFrame.txtBatchCode.getText();
String Starttime = EditFrame.txtStartTime.getText();
try {
/* Call the overrided setpersondetails() member procedure to set the
updated values to the object*/ personObj = pstudent.setpersondetails(Grade,Yearofcompletion,
Coursestaken,Hours,Batchcode,Starttime);
} catch(Exception e){ // Trap errors
gui.putStatus("Error while setting parttime student: "+e.toString());
}
} else if(personObj instanceof Student) {
// Get the student object
Student student = (Student)personObj;
// Get the edited values
String Grade = EditFrame.txtGrade.getText();
String Yearofcompletion = EditFrame.txtYearofCompletion.getText();
String Coursestaken = EditFrame.txtCoursesTaken.getText();
try {
/* Call the overrided setpersondetails() member procedure to set the
updated values to the object*/ personObj = student.setpersondetails(Grade,Yearofcompletion,Coursestaken);
} catch(Exception e){ // Trap errors
gui.putStatus("Error while setting student details : "+e.toString());
}
} else if(personObj instanceof Teacher) {
// Get the student object
Teacher teacher = (Teacher)personObj;
// Get the edited values
BigDecimal Experience = new BigDecimal(EditFrame.txtExperience.getText());
BigDecimal Salary = new BigDecimal(EditFrame.txtSalary.getText());
String Courseshandled = EditFrame.txtCoursesHandled.getText();
try {
/* Call the overrided setpersondetails() member procedure to set the
updated values to the object*/
personObj = teacher.setpersondetails(Experience,Salary,Courseshandled);
} catch(Exception e){ // Trap errors
gui.putStatus("Error while setting teacher details: "+e.toString());
}
}
// return the updated person object
return((Person)personObj);
}

/**
* This method gets the ssn of the person who has been selected in the JTable
* and retrieves the person's object from the database.
*/

private Person getSelectedPerson() {
Person personObj = null;
// Get the selected SSN in the JTable(personTable)
String ssn = getSSNo();
#sql iterator objectIter (Person);
objectIter tempIter=null;
// If not selected , return
if(!ssn.equals("NS")){
try {
//select person object from PERSONDETAILS table type
#sql tempIter={SELECT P.PERSON FROM PERSONDETAILS P WHERE P.PERSON.ssn=:ssn};
#sql { FETCH :tempIter INTO :personObj};
} catch(Exception ex) { // Trap errors
gui.putStatus("Error while Selecting person : "+ex.toString());
} finally {
try {
tempIter.close();
} catch(SQLException sqe){
gui.putStatus("Error while Displaying : "+sqe.toString());
}
}
}
// Return the person object
return(personObj);
}
/**
* This method returns the selected person's SSN from the JTable
*/

private String getSSNo() {
// Get the selected row number
int selectedRow = gui.personTable.getSelectedRow();
// If no rows are selected , return "NS" - Not Selected
if(selectedRow==-1) {
gui.putStatus(" Select a Person from the Table ...");
return("NS");
}
// Check if the object type is not other sub-types of person , since
// only student,teacher and parttimeStudent objects are handled
String objType=(String)gui.tableModel.getValueAt(selectedRow,2);
if(objType.equals(" O ")) {
gui.putStatus("The selected person is some other sub type of person .");
return("NS");
}
// Get the SSN from table
String ssnNo = (String)gui.tableModel.getValueAt(selectedRow,0);
// return the SSN
return(ssnNo);
}

/**
* This method performs the clean up action and closes the application
*/
private void exitApplication(){
// if connected to database
try {
Oracle.close();
} catch (SQLException ex){ // Trap errors
gui.putStatus(" Error while Closing the connection: "+ex.toString());
}
// Close the application
System.exit(0);
}
}//End of class
E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy