
Practical Database Programming With Java
.pdf
8.6 Build Java Web Project to Access and Manipulate Oracle Database 737
•Phone: 750-378-1148
•College: Florida Atlantic University
•Email: ybai@college.edu
One point to be noted is that when you modify each column for the updated record, you must
1.Press the Enter key for each modified column to make it active.
2.Click on the Commit Record button on the top of this table to make the modification for the row effective after the entire row has been modified.
Next, let’s discuss how to delete an existing faculty record from our database using the JSF faces and Java beans with the help of the Hibernate APIs.
8.6.10.4 Add the Codes to the Java Managed Bean to Manage Data Deleting
To begin this coding process, let’s first add a new method Delete() into our managed bean FacultyMBean.java. Recall that in Section 8.6.8.1, we have bound this method to the action attribute of the <h:commandButton id=″Delete″> tag in our JSF page
FacultyPage.jsp.
Open the code window of our managed bean FacultyMBean.java and add a new method Delete() into that file with the codes that are shown in Figure 8.153.
Recall that in Section 8.6.8.1, when we modified our JSF page FacultyPage.jsp file, we added one command tag shown below to that page:
<h:commandButton id=″Delete″ action=″#{FacultyMBean.Delete}″ value=″Delete″ />
With this tag, the Delete() method we just added into our managed bean has been bound to the action attribute of that tag, and this method will be called and executed as soon as the user clicks the Delete button on our JSF page FacultyPage.jsp as the project runs.
Let’s have a closer look at this piece of newly added codes to see how it works.
A.Some local variables are created first for this method. The delete is a boolean variable used to hold the running status of the DeleteFaculty() method defined in the session bean
public String Delete() {
Aboolean delete = false;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
Bdelete = facultySessionBean.DeleteFaculty(facultyID);
Cif (!delete) {
msgDlg.setMessage("The faculty deleting is failed!"); msgDlg.setVisible(true);
}
D return null;
}
Figure 8.153. The codes for the newly added method Delete().

738 Chapter 8 Developing Java Web Applications to Access Databases
class, and we will build this method in the next section. The msgDlg is a JDialog instance used to display the debug or exception information as the project runs.
B.The DeleteFaculty() method defined in our session bean, which will be developed in the next section, is called to perform this faculty record deleting action. The argument passed into that method is the faculty_id of the selected faculty that will be deleted. The running result of that method is returned and assigned to the local variable delete.
C.If the running result of the method DeleteFaculty() is false, which means that the data deleting has failed, this situation is displayed by executing the setMessage() method in the msgDlg instance.
D.A null is returned since this returning value is not important to this application.
Next, let’s develop the DeleteFaculty() method in our session bean class to perform the data deleting action using the Hibernate API.
8.6.10.5 Build the DeleteFaculty() Method in the Session Bean to Perform Data Deleting
Open the code window for our session bean class FacultySessionBean.java, and enter the codes shown in Figure 8.154 into this file to create a new method DeleteFaculty() and its codes.
Let’s have a closer look at this piece of new codes to see how it works.
A.A new instance of the JDialog class msgDlg is created, since we need to use it to display some debug information during the project running.
B.A try catch block is used to perform this data deleting action. First, a new SessionFactory object fact is created by executing the buildSessionFactory() method. Then, the session object is opened by executing the openSession() method.
public boolean DeleteFaculty(String fid) {
AMsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
Btry {
SessionFactory fact = new Configuration().configure().buildSessionFactory(); session = fact.openSession();
Corg.hibernate.Transaction tx = session.beginTransaction();
Dif (!tx.isActive())
tx.begin();
EFaculty ft = (Faculty)session.get(Faculty.class, fid);
Fsession.delete(ft);
Gtx.commit();
Hsession.close();
Ireturn true;
}
Jcatch(Exception e) { msgDlg.setMessage(e.getMessage()); msgDlg.setVisible(true);
Kreturn false;
}
}
Figure 8.154. The codes for the DeleteFaculty() method in the session bean.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 739
C.A new Transaction object tx is created to help to perform this data deleting action.
D.If this new Transaction instance has not been active, the begin() method is executed to begin this transaction instance.
E.The get() method in the session class is first executed to perform a query to retrieve an existing faculty record from the Faculty table based on the facultyID property. The first argument of this get() method is the class type Faculty, and the second argument is the facultyID property. The returned query result is assigned to a new Faculty instance ft. A point to be noted is that the Faculty class must be casted before this method to make sure that the session object returns an appropriate object.
F.The deleting action is performed by executing the delete() method for the session object with the Faculty entity object ft as the argument of this method.
G.The commit() method is executed to actually trigger and perform this data deleting action.
H.The close() method is executed to close this opened session object when this data deleting is complete.
I.Finally, a true is returned to the calling method to indicate the success of this data deleting action.
J.The catch block is used to track and detect any exception during this data deleting action. The exception information will be displayed using the JDialog instance msgDlg.
K.A false is returned if any exception occurred during this data deleting process.
Now let’s build and run the project to test this data deleting function.
8.6.10.6 Run the Project to Test the Faculty Record Deleting Action
Click on the Clean and Build Main Project button to build our project. If everything is fine, right click on our JSF page FacultyPage.jsp from the Projects window and select the Run File item to run the project. Of course you can run the project by starting from the LogIn page.
On the opened Faculty Page, type a desired faculty name to be deleted, such as Ying Bai, into the Faculty Name field to first perform a query for that faculty member. Then click on the Delete button to try to delete this faculty record from the Faculty table in our sample database.
To check and confirm this data deleting action, open the Faculty table from our sample Oracle database in the NetBeans IDE by performing the following operations:
A.Open the Services window and expand the Databases node.
B.Right click on our Oracle database URL: jdbc:oracle:thin:@localhost:1521:XE [CSE_ DEPT on CSE_DEPT], and select the Connect item to connect to our database.
C.Expand our sample database CSE_DEPT and Tables.
D.Right click on the Faculty table and select the View Data item.
It can be found from the opened Faculty table that the faculty record with the faculty_id of B78880 has been successfully deleted from the Faculty table. Our data deleting action is successful!
It is highly recommended to recover this deleted faculty record in our database since we want to keep our database clean. The point is that when we delete a faculty member

740 Chapter 8 Developing Java Web Applications to Access Databases
from the Faculty table, the related records to that deleted faculty in those child tables will also be deleted since a cascaded deleting relationship has been set up between the parent and child tables when we built this database in Chapter 2. Therefore, the faculty login record in the LogIn table and all courses taught by that faculty in the Course table will be deleted when the faculty member is deleted from the Faculty table. Also, because the Course table is a parent table for the StudentCourse table, all courses taken by students and taught by the deleted faculty will also be deleted from the StudentCourse table. To recover these deleted records, one needs to recover all of those deleted records. You can directly do these recoveries in the NetBeans IDE environment by opening each table in the Services window and inserting the original information back as new rows to each table.
Refer to Tables 8.4–8.7 in Section 8.5.5.4 to recover these deleted records.
One point to be noted is that when you insert each column for a new record, you must
1.First click on the Insert Record button on the top of this table to open a new Insert Record wizard.
2.Enter the original faculty information piece by piece to each column.
3.Press the Enter key at the end of each inserted column to make it active.
4.Click on the Commit Record button on the top of this table to make the insertion effective after the entire row has been inserted.
Your finished Insert Record wizard should match one that is shown in Figure 8.155. Click on the Add Row button to insert this row into the Faculty table to complete this data recovery.
The final coding job is for the Back button. The function of this coding is that the program should be directed to the SelectionPage.jsp page to enable users to make other actions when this button is clicked by the user.
Figure 8.155. The finished Insert Record wizard.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 741
public String Back() {
A return "SELECTION";
}
Figure 8.156. The codes for the Back() method.
8.6.10.7 Build the Codes for the Back Button Action Attribute in JSF Page
First let’s add a new method Back() to our managed bean class FacultyMBean.java. Recall that in Section 8.6.8.1, when we modified our JSF page FacultyPage.jsp file,
we added one command tag shown below to that page:
<h:commandButton id=″Back″ action=″#{FacultyMBean.Back}″ value=″Back″ />
With this tag, the Back() method we just added into our managed bean has been bound to the action attribute of that tag, and this method will be called and executed as soon as the user clicks the Back button on our JSF page FacultyPage.jsp as the project runs.
Recall that when we built the navigation relationship between our LogIn, Selection, Error, and Faculty pages in Section 8.6.8.5, we have set up these navigation rules using the configuration file faces-config.xml. The relationship between the Faculty and the Selection pages has been determined by two rules, which is a round trip between these two pages. Refer to that section to get a detailed and clear picture for this relationship.
The coding job is very simple for this Back button. Open the code window of our managed bean FacultyMBean.java, and enter the codes shown in Figure 8.156 into the Back() method we just added into this class.
As shown in step A in Figure 8.156, this coding is very simple and a return “SELECTION” is executed as this Back button is clicked by the user. Refer to our Web configure file faces-config.xml, and you can find that the navigation rule from the Faculty page to the Selection page has been defined by a string “SELECTION”. The point to be noted is that the returned string in this Back() method must be exactly identical with that string defined in the configuration file to enable this navigation rule effective.
Next, let’s discuss how to query and manipulate data against the Course table in our database using the JSF faces and Java beans with the help of the Hibernate APIs.
8.6.11 Query Data from the Course Table Using JavaServer Faces and Java Beans
In Section 8.5, we discussed how to build a Web project JavaWebDBJSPSQL to access and manipulate our sample SQL Server database using different techniques. Especially in Section 8.5.6, we introduced how to access and manipulate data against the
Course table using the JavaServer faces and Java beans. The only differences between that project and our current project are data sources and data manipulating tool. In our current project, the data source is Oracle database, and the manipulating tool is the Hibernate APIs.

742 Chapter 8 Developing Java Web Applications to Access Databases
Because of some similarity between the coding processes for these two projects, we will concentrate on these two different parts in the following development.
Recall that in Section 8.5.6.1, we modified our JSP page Course.jsp to a JavaServer
Face page CoursePage.jsp when we built our project JavaWebDBJSPSQL. In this section, we want to use that page as our JSF page to perform data queries and actions against the Course table in our sample Oracle database. Perform the following operations to add this page into our current project:
1.Go to the Wiley ftp site (refer to Figure 1.2 in Chapter 1)
2.Open the folder JSP Files that is located in that site.
3.Copy the JSF file CoursePage.jsp from that folder.
4.Open our current project JavaWebDBJSPOracle and the Files window, and paste the copied JSF page CoursePage.jsp to the web folder under our opened project.
Now if you open the JSF page CoursePage.jsp, you can find that all inputText fields and commandButtons in that page have been bound to associated properties defined in a managed bean CourseBean.java class file.
As we did in Section 8.5, we still want to divide this course information query and manipulation into two parts: the Java managed bean CourseBean.java, which is used to controlandmanagethecoursedataactions,andtheJavasessionbeanCourseSessionBean. java, which is used to perform the actual course data actions using the Hibernate API tool.
First, let’s create our Java managed bean class CourseBean.java and use some codes from the JSF page CourseBean.java we built in Section 8.5.6.2 from the project
JavaWebDBJSPSQL.
8.6.11.1 Build the JavaServer Face Managed Bean CourseBean
Perform the following operations to create this JSF managed bean class:
1.Launch the NetBeans IDE and open our Web application project JavaWebDBJSPOracle.
2.Right click on our project JavaWebDBJSPOracle from the Projects window and select the New > Other item to open the New File wizard.
3.Select JavaServer Faces from the Categories list and JSF Managed Bean from the
File Types list. Then click on the Next button.
4. Enter CourseBean into the Class Name field, and select the JavaWebDBJSPOracle from the Package combo box.
5.Make sure to check the Add data to configuration file checkbox since we want to add this bean class into our Web configuration file to build a navigation rule later. Then select the session from the Scope combo box and click on the Finish button.
On the opened CourseBean class file, enter the first part of the codes, which is shown in Figure 8.157, into this managed bean. The new added codes have been highlighted in bold.In fact,most of codes are identical with those in the managed bean class CourseBean. java in the project JavaWebDBJSPSQL we built in Section 8.5, and you can copy and paste them in this class.
Let’s have a closer look at the codes in this part to see how they work.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 743
package JavaWebDBJSPOracle;
Aimport java.util.*;
import javax.faces.model.SelectItem; public class CourseBean {
Bprivate String courseName; private String schedule; private String classroom; private String credit; private String enrollment; private String courseID; private String facultyName; private List courseList;
private String selectedItem = null;
CMsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
public CourseBean() {
}
Dpublic void setSelectedItem(String cid) {
selectedItem = cid;
}
E public String getSelectedItem() { return selectedItem;
}
F public void setCourseList(List cid) { courseList = cid;
}
G public List getCourseList() { return courseList;
}
H public String getFacultyName() { return facultyName;
}
I public void setFacultyName(String FacultyName) { this.facultyName = FacultyName;
}
J public String getCourseID() { return courseID;
}
K public void setCourseID(String CourseID) { this.courseID = CourseID;
}
L public String getEnrollment() { return enrollment;
}
M public void setEnrollment(String Enrollment) { this.enrollment = Enrollment;
}
N public String getCredit() { return credit;
}
O public void setCredit(String Credit) { this.credit = Credit;
}
P public String getClassroom() { return classroom;
}
Q public void setClassroom(String Classroom) { this.classroom = Classroom;
}
………
Figure 8.157. The first part codes of the CourseBean class.

744Chapter 8 Developing Java Web Applications to Access Databases
A.First, some useful Java packages are defined, since we will use some classes and components that are defined in those packages.
B.Then seven properties, which should be bound to the associated attributes of tags in the CoursePage.jsp JSF page, are declared. The point to be noted is that the names of these properties must be identical with those of attributes defined in our Web view file,
CoursePage.jsp, including the cases since Java is a case-sensitive language. Also the List collection courseList, which is bound to the value attribute of the <f:selectItems>
tag, and the selectedItem, which is bound to the value attribute of the <h:selectOneListbox> tag, are declared here, too.
C.The msgDlg is a new instance of our customer-built dialog box, and this is used to display our testing and debug information when we test the codes in this file later.
D.Starting from step D through step Q, seven setter and getter methods are defined for seven properties we defined above. These methods are used to set or get each property defined in this Java bean class as the project runs.
Now let’s enter the second part of the codes into this Java bean class and locate them just below the first part codes, as show in Figure 8.158.
Let’s have a closer look at the codes in this part to see how they work.
A.From steps A through to D, another two-set setter and getter methods are defined and they are used to set and get two properties, schedule and courseName, defined in this bean class.
E.The Select() method, which is bound to the action attribute of the Select button on the CoursePage file, is defined here. This method will be called and executed as the Select button in the CoursePage.jsp is clicked by the user as the project runs. To use the List collection, first, a new ArrayList instance is created.
F.A new List instance, cList, is also created, and it is used to hold the queried result from calling the getCourseID() method that is defined in the session bean class CourseSessionBean.java that will be built in the next section. This method will return a List of course_id taught by the selected faculty by the user from the CoursePage as the project runs.
G.A for loop is utilized to pick up each course_id from the cList instance and assign it to a new instance of SelectItem class, courseid, and add it into the courseList property using the Add() method. A point to be noted is that the returned course_id must be converted to an instance of the class interface SelectItem that is in the package javax.faces.model, and then it can be added into the List collection.
H.Because the returned value is not important for this application, a null is returned when this method is done.
I.The Details() method, which is bound to the action attribute of the Details button on the CoursePage file, is defined here. This method will be called and executed as the Details button in the CoursePage.jsp page is clicked by the user as the project runs. This method will return five pieces of detailed course information based on the selected course_id from the courseList box in the CoursePage as the project runs, and the returned five pieces of course information will be displayed in five inputText fields in that page. The selected
course_id, which is stored in the selectedItem property in our JSF managed bean CourseBean and has been bound to the value attribute of the <h:selectOneListbox> tag in the CoursePage, will be checked first to make sure that a valid course_id has been selected by the user.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 745
A public String getSchedule() { return schedule;
}
B public void setSchedule(String Schedule) { this.schedule = Schedule;
}
C public String getCourseName() { return courseName;
}
D public void setCourseName(String CourseName) { this.courseName = CourseName;
}
Epublic String Select() { courseList = new ArrayList();
FList cList = courseSessionBean.getCourseID(getFacultyName());
Gfor (int i=0; i < cList.size(); i++) {
SelectItem courseid = new SelectItem(cList.get(i).toString()); courseList.add(courseid);
}
Hreturn null;
}
Ipublic Boolean Details() {
if (selectedItem != null) {
JList<Object[]> courseDetail = courseSessionBean.getCourseDetail(selectedItem);
Kfor (Object[] result:courseDetail){ courseName = (String)result[0]; schedule = (String)result[1]; classroom = (String)result[2]; credit = result[3].toString();
|
enrollment = result[4].toString(); |
|
} |
|
} |
L |
else { |
|
msgDlg.setMessage("the selected courseID is invalid!"); |
|
msgDlg.setVisible(true); |
|
} |
Mreturn null;
}
Npublic Boolean Update() { return null;
}
O public Boolean Delete() { return null;
}
P public String Back() {
}
}
Figure 8.158. The second part codes of the CourseBean class.
J.If the selectedItem property is non-null, which means that a valid course_id has been selected, the getCourseDetail() method defined in our session bean class CourseSessionBean that will be built in the next section, will be called to retrieve five pieces of detailed information for the selected course_id, and assign them to a List object courseDetail.

746Chapter 8 Developing Java Web Applications to Access Databases
K.An enhanced for loop is used to retrieve the detailed course information from the query result list and assign them one by one to the associated properties defined in our JSF managed bean class CourseBean.
L.If the selectedItem property contains a null value, which means that no valid course_id has been selected. A warning message is displayed for this situation using the msgDlg.
M.Since the returned value of this method is not important to us, a null is used.
N.Three other methods, Update(), Delete(), and Back(), which are bound to the action attributes of the associated buttons in the CoursePage file, are defined in steps N, O, and P in this Java bean class. We will develop the codes to execute the data updating and deleting actions against our sample database later using these methods. The Back() method is used to return to the Selection.jsp page.
After finishing the code development for this bean, you may encounter some realtime compiling errors indicated with either red or blue underscored lines. One reason for this is that some packages are missed when you try to use some classes or interfaces in this code development process. To fix that, right click on this coding window and select the Fix Imports item from the pop-up menu to add required packages. An example is the List class that is located at the java.util package, and an import java.util.List statement should have been added into this bean after you had performed the Fix Imports operation. Since we need to use the ArrayList class that is also located at the java.util package, so we need to modify this import statement to import java.util.*.
Another package you may need to use for this bean is the javax.faces.model, since we need to use the SelectItem component as an element in the <h:selectOneListbox> tag. Therefore, add another import statement to this bean, import javax.faces.model. SelectItem. Your finished import package block should match one that is shown in step A in Figure 8.157. The modified import statements have been highlighted in bold.
Next, let’s develop and build our session bean class CourseSessionBean.java to handle database-related operations using the Hibernate APIs.
8.6.11.2 Build the Java Session Bean CourseSessionBean
The purpose of this session bean is to directly access our sample Oracle database and perform all course data queries and manipulations against our database via the Hibernate API.
Perform the following operations to create a new session bean class
CourseSessionBean.java:
1.Right click on our project JavaWebDBJSPOracle from the Projects window, and select the New > Other item to open the New File wizard.
2.Select Java EE from the Categories list and Session Bean from the File Types list, and then click on the Next button.
3.Enter CourseSessionBean into the Class Name field. Select the JavaWebDBJSPOracle from the Package combo box, and check the Stateless radio button from the Session Type group. Your finished Name and Location wizard should match one that is shown in Figure 8.159. Click on the Finish button to complete this session bean creation process.
On the opened CourseSessionBean.java class file, perform the following operations to create the codes for this file, which is shown in Figure 8.160.