JAVA RUNTIME OBJECTS METHOD
8.6 BUILD JAVA WEB PROJECT TO ACCESS AND MANIPULATE ORACLE DATABASE
8.6.12 Update and Delete Records for the Course Table Using
First, let ’ s handle the course record updating action.
Because of the complexity in updating a course record with the primary key course_
id , in this section, we still want to update a course record with an existing course_id . In other words, we will update a course record by changing all columns without touching the course_id column, since one needs to update this course_id fi rst in the child table (StudentCourse table) before he can update it in the parent table (Course) if one wants to update this course_id column.
As we did for the course information query in the last section, we can divide this course record updating action into two Java beans: the Java managed bean CourseBean.
java that is used to manage and control the data updating, and the session bean
CourseSessionBean.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.12.1 Add the Codes to the Java Managed Bean to Manage Data Updating Recall that in Section 8.6.11.1 , when we built our managed bean CourseBean.java; in total, we created fi ve user - defi ned methods, Select() , Details() , Update() , Delete() , and Back() in that bean class. All of these fi ve methods have been bound to the action attri- butes of the associated <h:commandButton > tags in our JSF page CoursePage.jsp . We have developed and built the codes for the fi rst two methods Select() and Details() in the previous sections to perform the course information queries. Now let ’ s build the codes for the Update() method to perform the course information updating actions.
Open the code window of our managed bean CourseBean.java and add the codes that are shown in Figure 8.165 into this method.
c08.indd 754
c08.indd 754 7/20/2011 11:12:39 AM7/20/2011 11:12:39 AM
www.traintelco.com
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 UpdateCourse() method defi ned in the session bean class, and we will build this method in the next section. The cUpdate[] is a string array used to hold fi ve pieces of updating course information for an existing record in the Course table in our sample database. The point to be noted is that we used fi ve properties defi ned in this managed bean as fi ve pieces of updating course information since those properties have been bound to the associated value attributes of the <h:inputText > tags in our JSF page CoursePage.jsp . Furthermore, those properties can be automatically updated as the users enter fi ve pieces of updating course information into fi ve text fi elds related to those tags in our JSF page CoursePage.jsp . The sixth parameter in the cUpdate[] array is the property courseID selected by the user from the course listbox, and it is used to work as a query criterion.
B. The UpdateCourse() method defi ned in our session bean, which will be developed in the next section, is called to perform this course record updating. The argument passed into that method is the string array cUpdate[] , which contains fi ve pieces of updated course information, and the query criterion courseID . The running result of that method is returned and assigned to the local variable update .
C. If the running result of the method UpdateCourse() is false , which means that the data updating 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 UpdateCourse() method in our session bean class to perform the course data updating using the Hibernate API.
8.6.12.2 Build the UpdateCourse() Method in the Session Bean to Perform Data Updating
Open the code window for our session bean class CourseSessionBean.java and enter the codes shown in Figure 8.166 into this fi le to create a new method UpdateCourse() and its codes.
Let ’ s have a closer look at this piece of new codes to see how it works.
A. Two packages are added into this session bean class. The fi rst is used for components to confi gure the session factory, and the second is used for the data conversion.
Figure 8.165. The codes for the method Update().
public Boolean Update() { boolean update = false;
String[] cUpdate = {courseName, schedule, classroom, credit, enrollment, selectedItem};
update = courseSessionBean.UpdateCourse(cUpdate);
if (!update) {
msgDlg.setMessage("The course updating is failed!");
msgDlg.setVisible(true);
}
return null;
} A B C
D
B. 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.
C. 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.
D. A new Transaction object tx is created to help to perform this data updating action.
E. If this new Transaction instance has not been active, the begin() method is executed to begin this transaction instance.
F. The get() method in the session class is fi rst executed to perform a query to retrieve an existing course record from the Course table based on the course_id that is stored in the string array nCourse[5] . The fi rst argument of this get() method is the class type Course, and the second argument is the course_id . The returned query result is assigned to a new Course instance cs . A point to be noted is that the Course class must be casted before this method to make sure that the session object returns an appropriate object.
G. Five setter methods are executed to set up fi ve pieces of updated course information to the new created Course entity object cs .
H. Two points to be noted for this step is the data type conversions between the Java.lang.
String and the java.meth.BigDecimal . The required data type of the arguments for the
setCredit() and setEnrollment() methods are java.meth.BigDecimal . However, the
Figure 8.166. The codes for the UpdateFaculty() method in the session bean.
import org.hibernate.cfg.Configuration;
import java.math.BigDecimal;
………
public boolean UpdateCourse(String[] nCourse) {
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();
Course cs = (Course)session.get(Course.class, nCourse[5]);
cs.setCourse(nCourse[0]);
cs.setSchedule(nCourse[1]);
cs.setClassroom(nCourse[2]);
BigDecimal decCredit = new BigDecimal(nCourse[3]);
cs.setCredit(decCredit);
BigDecimal decEnroll = new BigDecimal(nCourse[4]);
cs.setEnrollment(decEnroll);
session.update(cs);
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 M N
c08.indd 756
c08.indd 756 7/20/2011 11:12:39 AM7/20/2011 11:12:39 AM
www.traintelco.com
updating parameters stored in the nCourse[] array are java.lang.String . Therefore, it is necessary to perform a conversion between these two different data types. In steps H and I , we created two new instances of the BigDecimal class and used the constructor of this class to complete this conversion. This is an easy and convenient way to do this conversion.
J. The updating action is performed by executing the update() method for the session object with the Course entity object cs as the argument of this method.
K. The commit() method is executed to actually trigger and perform this data updating action.
L. The close() method is executed to close this opened session object when this data updating is complete.
M. Finally, a true is returned to the calling method to indicate the success of this data updating action.
N. 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 , and a
false is returned if any exception occurred during this data updating process.
Now let ’ s build and run the project to test this course data updating function.
8.6.12.3 Run the Project to Test the Course 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 CoursePage.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 Course Page, type a desired faculty name, such as Ying Bai , into the
Faculty Name fi eld to perform a course information query for that faculty member.
Then select the fi rst course_id from the course listbox, which is CSC - 132B , and click on the Details button to pick up the detailed information for this course. To update this course, just enter fi ve pieces of updated course information shown in Figure 8.167 into
Figure 8.167. The updated course information.
the associated fi ve fi elds as an updated course record. Then click on the Update button to try to update this course record against the Course table in our sample database.
To check and confi rm this data updating action, you have two ways to go. The fi rst and easiest way is to try to retrieve this updated course record. To do that, select another
course_id , such as CSE - 438 , from the course listbox, and click on the Details button to query and display detailed information for that course. Then select the course CSC - 132B from the course listbox and click on the Details button again to try to retrieve this updated course. You can fi nd that this course has been successfully updated.
Another way to do this confi rmation is to open the Course 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 Course table and select the View Data item.
Your opened Course table is shown in Figure 8.168 .
It is found that the course record with the course_id of CSC - 132B , which is located at the sixth row on this table and has been highlighted in dark color, has been successfully updated with fi ve pieces of updated course information. Our course data updating action is successful!
It is highly recommended to recover this updated course 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 CoursePage.jsp to perform another course updating action by entering the original course information that is shown below for the course_id CSC - 132B and clicking on the Update button.
Figure 8.168. The updated course record.
c08.indd 758
c08.indd 758 7/20/2011 7:58:59 PM7/20/2011 7:58:59 PM
www.traintelco.com
The second way is that you can directly do this recovery by opening the Course table in the Services window and modifying the updated row with the original course informa- tion for the course_id CSC - 132B , which is listed below:
• Course: Introduction to Programming • Credit: 3
• Classroom: MTC - 302 • Schedule: T - H: 1:00 – 2:25 p.m.
• Enrollment: 21 • faculty_id: B78880
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 of the row effective after the entire row has been modifi ed.
Next, let ’ s discuss how to delete an existing course record from our database using the JSF faces and Java beans with the help of the Hibernate APIs.
8.6.12.4 Add the Codes to the Java Managed Bean to Manage Data Deleting Recall that in Section 8.5.6.1 , we have bound this method to the action attribute of the
<h:commandButton id =″Delete ″> tag in our JSF page CoursePage.jsp . With this tag, the Delete() method in our managed bean has been bound to the action attribute of that tag, and it will be called and executed as soon as the user clicks the Delete button on our JSF page CoursePage.jsp as the project runs.
Open the code window of our managed bean CourseBean.java and add the codes that are shown in Figure 8.169 into this method.
Let ’ s have a closer look at this piece of newly added codes to see how it works.
A. A local variable delete is created and initialized fi rst for this method. This is a boolean variable used to hold the running status of the DeleteCourse() method defi ned in the session bean class, and we will build this method in the next section.
B. The DeleteCourse() method defi ned in our session bean, which will be developed in the next section, is called to perform this course record deleting action. The argument passed
Figure 8.169. The codes for the method Delete().
public Boolean Delete() { boolean delete = false;
delete = courseSessionBean.DeleteCourse(selectedItem);
if (!delete) {
msgDlg.setMessage("The course deleting is failed!");
msgDlg.setVisible(true);
}
return null;
} A B C
D
into that method is a course_id that is stored in the selectedItem property, and will be deleted from our Course table. The running result of that method is returned and assigned to the local variable delete .
C. If the running result of the method DeleteCourse() is false , which means that the data deleting has failed, this situation is displayed by executing the setMessage() method in the msgDlg instance.
D. Otherwise, if a true returned, which means that this course data deleting is successful, a null is returned since this returning value is not important to this application.
Next, let ’ s develop the DeleteCourse() method in our session bean class to perform the course data deleting action using the Hibernate API.
8.6.12.5 Build the DeleteCourse() Method in the Session Bean to Perform Data Deleting
Open the code window for our session bean class CourseSessionBean.java and enter the codes shown in Figure 8.170 into this fi le to create a new method DeleteCourse() 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.
C. A new Transaction object tx is created to help to perform this data deleting action.
Figure 8.170. The codes for the DeleteCourse() method in the session bean.
public boolean DeleteCourse(String cid) {
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();
Course cs = (Course)session.get(Course.class, cid);
session.delete(cs);
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 760
c08.indd 760 7/20/2011 11:12:39 AM7/20/2011 11:12:39 AM
www.traintelco.com
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 course record from the Course table based on the courseID that is stored in the input argument cid . The fi rst argument of this get() method is the class type Course, and the second argument is the courseID property. The returned query result is assigned to a new Course instance cs . A point to be noted is that the Course 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 Course entity object cs 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 course data deleting function. You can run the project in two ways: either run the single page CoursePage.jsp , or run the entire project starting from the LogInPage.jsp . Let ’ s fi rst run the project in the fi rst way.
8.6.12.6 Run the Project to Test the Course 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 CoursePage.jsp from the Projects window and select the Run File item to run the project.
On the opened Course Page, fi rst, we need to perform a course information query based on a desired faculty. Type a faculty name, such as Jenney King , into the Faculty Name fi eld and click on the Select button to retrieve all courses ( course_id ) taught by that selected faculty.
To delete a course, select a course_id from the course listbox, such as CSC - 233B , and click on the Delete button to try to delete it from the Course table in our sample database.
To check and confi rm this data deleting action, open the Course 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 Course table and select the View Data item.
It can be found from the opened Course table that the course record with the
course_id of CSC - 233B has been successfully deleted from the Course table. Our data deleting action is successful!