JAVA RUNTIME OBJECTS METHOD
8.6 BUILD JAVA WEB PROJECT TO ACCESS AND MANIPULATE ORACLE DATABASE
8.6.10 Update and Delete Records from the Faculty Table
First, let ’ s handle the faculty record updating action.
Because of the complex in updating a faculty record with the primary key faculty_id , in this section, we still want to update a faculty record with an existing faculty_id . In other words, we will update a faculty record by changing all columns without touching the faculty_id column since one needs to update this faculty_id fi rst in the child tables (LogIn and Course) before he can update it in the parent table (Faculty) if one wants to update this faculty_id column.
As we did for the new faculty record insertion in the last section, we can divide this faculty record updating action into two Java beans: the Java managed bean FacultyMBean.
java that is used to manage and control the data updating, and the session bean
FacultySessionBean.java that is used to perform the actual data updating actions.
First, let ’ s build the codes for the managed bean to manage this data updating action.
8.6.10.1 Add the Codes to the Java Managed Bean to Manage Data Updating To begin this coding process, let ’ s fi rst add a new method Update() into our managed bean FacultyMBean.java . Recall that in Section 8.6.8.1 , we have bound this method to the <h:commandButton id =″Update ″> tag in our JSF page FacultyPage.jsp .
Open the code window of our managed bean FacultyMBean.java and add a new method Update() into that fi le with the codes that are shown in Figure 8.149 .
Recall that in Section 8.6.8.1 , when we modifi ed our JSF page FacultyPage.jsp fi le, we added one command tag shown below to that page:
<h:commandButton id =″Update ″ action =″#{FacultyMBean.Update} ″ value =″Update ″ / >
Figure 8.148. The opened Faculty table in the NetBeans IDE.
c08.indd 732
c08.indd 732 7/20/2011 11:12:36 AM7/20/2011 11:12:36 AM
www.traintelco.com
With this tag, the Update() 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 Update 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 fi rst for this method. The update is a boolean variable used to hold the running status of the UpdateFaculty() method defi ned in the session bean 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. The fUpdate[] is a string array used to hold six pieces of updating faculty information for an existing record in the Faculty table in our sample database. The point to be noted is that we used six properties defi ned in this managed bean as six pieces of updating faculty information, since those properties have been bound to the associated value attributes of the <h:inputText >
tags in our JSF page FacultyPage.jsp . Furthermore, those properties can be automatically updated as the users enter six pieces of updating faculty information into six text fi elds related to those tags in our JSF page FacultyPage.jsp . The seventh parameter in the
fUpdate[] array is the property facultyID used to work as a query criterion.
B. If the user entered an updated faculty image ’ s name into the Image fi eld in the JSF page, the property facultyImageName defi ned in the managed bean should contain a valid faculty image fi le ’ s name, and this name is assigned to the property facultyImage that will be used to display this updated image later.
C. The UpdateFaculty() method defi ned in our session bean, which will be developed in the next section, is called to perform this faculty record updating. The argument passed into that method is the string array fUpdate[] that contains six pieces of updated faculty infor- mation. The running result of that method is returned and assigned to the local variable
update .
D. If the running result of the method UpdateFaculty() is false , which means that the data updating has failed, this situation is displayed by executing the setMessage() method in the msgDlg instance.
E. A null is returned since this returning value is not important to this application.
Next, let ’ s develop the UpdateFaculty() method in our session bean class to perform the data updating using the Hibernate API.
Figure 8.149. The codes for the newly added method Update().
public String Update() { boolean update = false;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
String[] fUpdate = {name, office, phone, college, title, email, facultyID};
if (facultyImageName != null) facultyImage = facultyImageName;
update = facultySessionBean.UpdateFaculty(fUpdate);
if (!update) {
msgDlg.setMessage("The faculty updating is failed!");
msgDlg.setVisible(true);
}
return null;
} A
B C D
E
8.6.10.2 Build the UpdateFaculty() Method in the Session Bean to Perform Data Updating
Open the code window for our session bean class FacultySessionBean.java and enter the codes shown in Figure 8.150 into this fi le to create a new method UpdateFaculty() 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 updating 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.
C. A new Transaction object tx is created to help to perform this data updating 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 fi rst executed to perform a query to retrieve an existing faculty record from the Faculty table based on the faculty_id that is stored in the string array upFaculty[6] . The fi rst argument of this get() method is the class type Faculty, and the second argument is the faculty_id . 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.
Figure 8.150. The codes for the UpdateFaculty() method in the session bean.
public boolean UpdateFaculty(String[] upFaculty) {
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
try {
SessionFactory fact = new Configuration().configure().buildSessionFactory();
session = fact.openSession();
org.hibernate.Transaction tx = session.beginTransaction();
if (!tx.isActive()) tx.begin();
Faculty ft = (Faculty)session.get(Faculty.class, upFaculty[6]);
ft.setFacultyName(upFaculty[0]);
ft.setOffice(upFaculty[1]);
ft.setPhone(upFaculty[2]);
ft.setCollege(upFaculty[3]);
ft.setTitle(upFaculty[4]);
ft.setEmail(upFaculty[5]);
session.update(ft);
tx.commit();
session.close();
return true;
}
catch(Exception e) {
msgDlg.setMessage(e.getMessage());
msgDlg.setVisible(true);
return false;
} } A B
C D E F
G H I J K
L
c08.indd 734
c08.indd 734 7/20/2011 11:12:36 AM7/20/2011 11:12:36 AM
www.traintelco.com
F. Six setter methods are executed to set up six pieces of updated faculty information to the newly created Faculty entity object ft .
G. The updating action is performed by executing the update() method for the session object, with the Faculty entity object ft as the argument of this method.
H. The commit() method is executed to actually trigger and perform this data updating action.
I. The close() method is executed to close this opened session object when this data updating is complete.
J. Finally, a true is returned to the calling method to indicate the success of this data updating action.
K. The catch block is used to track and detect any exception during this data updating action.
The exception information will be displayed using the JDialog instance msgDlg . L. A false is returned if any exception occurred during this data updating process.
Now let ’ s build and run the project to test this data updating function.
8.6.10.3 Run the Project to Test the Faculty Record Updating Action
Click on the Clean and Build Main Project button to build our project. If everything is fi ne, 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, such as Ying Bai , into the
Faculty Name fi eld to perform a query for that faculty member. Then enter six pieces of updated faculty information shown in Figure 8.151 into the associated six fi elds as an updated faculty record. Also, enter the default faculty image fi le ’ s name, Default.jpg , into the Image fi eld as an updated image for this faculty, as shown in Figure 8.151 . Then click on the Update button to try to update this faculty record against the Faculty table in our sample database.
Figure 8.151. The updated faculty information.
To check and confi rm this data updating action, open the Faculty table from our sample Oracle database 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.
Your opened Faculty table is shown in Figure 8.152 .
It can be found that the faculty record with the faculty_id of B78880, which is located at the fi rst row on this table and has been highlighted in dark color, has been successfully updated with six pieces of updated faculty information. Our data updating action is successful!
It is highly recommended to recover this updated faculty record in our database, since we want to keep our database clean. To do this recovery, there are two ways to go.
The fi rst and the easiest way is to use this JSF page FacultyPage.jsp to perform another updating action by entering the original information that is shown below for the faculty member Ying Bai and clicking on the Update button. Make sure that the Image fi eld is empty when you use the fi rst way to recover that faculty information since we do not want to update the image for the faculty Ying Bai .
The second way is that you can directly do this recovery by opening the Faculty table in the Services window and modifying the updated row with the original faculty informa- tion for faculty member Ying Bai , which is listed below:
Figure 8.152. The updated faculty record.
• Name: Ying Bai
• Title: Associate Professor • Offi ce: MTC - 211
c08.indd 736
c08.indd 736 7/20/2011 11:12:37 AM7/20/2011 11:12:37 AM
www.traintelco.com
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 modifi ed column to make it active.
2. Click on the Commit Record button on the top of this table to make the modifi cation for the row effective after the entire row has been modifi ed.
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 fi rst 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 fi le with the codes that are shown in Figure 8.153 .
Recall that in Section 8.6.8.1 , when we modifi ed our JSF page FacultyPage.jsp fi le, 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 fi rst for this method. The delete is a boolean variable used to hold the running status of the DeleteFaculty() method defi ned in the session bean
Figure 8.153. The codes for the newly added method Delete().
public String Delete() { boolean delete = false;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
delete = facultySessionBean.DeleteFaculty(facultyID);
if (!delete) {
msgDlg.setMessage("The faculty deleting is failed!");
msgDlg.setVisible(true);
}
return null;
} A B C
D
• Phone: 750 - 378 - 1148
• College: Florida Atlantic University • Email: ybai@college.edu
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 defi ned 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 fi le 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.
Figure 8.154. The codes for the DeleteFaculty() method in the session bean.
public boolean DeleteFaculty(String fid) {
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
try {
SessionFactory fact = new Configuration().configure().buildSessionFactory();
session = fact.openSession();
org.hibernate.Transaction tx = session.beginTransaction();
if (!tx.isActive()) tx.begin();
Faculty ft = (Faculty)session.get(Faculty.class, fid);
session.delete(ft);
tx.commit();
session.close();
return true;
}
catch(Exception e) {
msgDlg.setMessage(e.getMessage());
msgDlg.setVisible(true);
return false;
} } A B
C D E F G H I J
K
c08.indd 738
c08.indd 738 7/20/2011 11:12:37 AM7/20/2011 11:12:37 AM
www.traintelco.com
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 fi rst executed to perform a query to retrieve an existing faculty record from the Faculty table based on the facultyID property. The fi rst 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 fi ne, 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 fi eld to fi rst 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 confi rm 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
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 fi nished 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 fi nal 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 fi nished Insert Record wizard.
c08.indd 740
c08.indd 740 7/20/2011 11:12:37 AM7/20/2011 11:12:37 AM
www.traintelco.com