JAVA RUNTIME OBJECTS METHOD
8.6 BUILD JAVA WEB PROJECT TO ACCESS AND MANIPULATE ORACLE DATABASE
8.6.11 Query Data from the Course Table Using JavaServer
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.
Figure 8.156. The codes for the Back() method.
public String Back() { return "SELECTION";
} A
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 modifi ed 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 fi le 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 fi nd that all inputText fi elds and commandButtons in that page have been bound to associated properties defi ned in a managed bean CourseBean.java class fi le.
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 control and manage the course data actions, and the Java session bean CourseSessionBean.
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 fi eld, and select the JavaWebDBJSPOracle from the Package combo box.
5. Make sure to check the Add data to confi guration fi le checkbox since we want to add this bean class into our Web confi guration fi le 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 fi le, enter the fi rst 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.
c08.indd 742
c08.indd 742 7/20/2011 11:12:38 AM7/20/2011 11:12:38 AM
www.traintelco.com
Figure 8.157. The fi rst part codes of the CourseBean class.
package JavaWebDBJSPOracle;
import java.util.*;
import javax.faces.model.SelectItem;
public class CourseBean { private 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;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
public CourseBean() { }
public void setSelectedItem(String cid) { selectedItem = cid;
}
public String getSelectedItem() { return selectedItem;
}
public void setCourseList(List cid) { courseList = cid;
}
public List getCourseList() { return courseList;
}
public String getFacultyName() { return facultyName;
}
public void setFacultyName(String FacultyName) { this.facultyName = FacultyName;
}
public String getCourseID() { return courseID;
}
public void setCourseID(String CourseID) { this.courseID = CourseID;
}
public String getEnrollment() { return enrollment;
}
public void setEnrollment(String Enrollment) { this.enrollment = Enrollment;
}
public String getCredit() { return credit;
}
public void setCredit(String Credit) { this.credit = Credit;
}
public String getClassroom() { return classroom;
}
public void setClassroom(String Classroom) { this.classroom = Classroom;
} ………
A
B
C
D E
F G
H I
J K
L M
N O
P Q
A. First, some useful Java packages are defi ned, since we will use some classes and components that are defi ned 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 defi ned in our Web view fi le,
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 fi le later.
D. Starting from step D through step Q , seven setter and getter methods are defi ned for seven properties we defi ned above. These methods are used to set or get each property defi ned 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 fi rst 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 defi ned and they are used to set and get two properties, schedule and courseName , defi ned in this bean class.
E. The Select() method, which is bound to the action attribute of the Select button on the
CoursePage fi le, is defi ned 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, fi rst, 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 defi ned 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 fi le, is defi ned 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 fi ve 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 fi ve pieces of course information will be displayed in fi ve inputText fi elds 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 fi rst to make sure that a valid course_id has been selected by the user.
c08.indd 744
c08.indd 744 7/20/2011 11:12:38 AM7/20/2011 11:12:38 AM
www.traintelco.com
Figure 8.158. The second part codes of the CourseBean class.
public String getSchedule() { return schedule;
}
public void setSchedule(String Schedule) { this.schedule = Schedule;
}
public String getCourseName() { return courseName;
}
public void setCourseName(String CourseName) { this.courseName = CourseName;
}
public String Select() {
courseList = new ArrayList();
List cList = courseSessionBean.getCourseID(getFacultyName());
for (int i=0; i < cList.size(); i++) {
SelectItem courseid = new SelectItem(cList.get(i).toString());
courseList.add(courseid);
}
return null;
}
public Boolean Details() { if (selectedItem != null) {
List<Object[]> courseDetail = courseSessionBean.getCourseDetail(selectedItem);
for (Object[] result:courseDetail){
courseName = (String)result[0];
schedule = (String)result[1];
classroom = (String)result[2];
credit = result[3].toString();
enrollment = result[4].toString();
} } else {
msgDlg.setMessage("the selected courseID is invalid!");
msgDlg.setVisible(true);
}
return null;
}
public Boolean Update() { return null;
}
public Boolean Delete() { return null;
}
public String Back() { }
} A
B
C
D
E F G
H I J K
L
M N
O
P
J. If the selectedItem property is non - null, which means that a valid course_id has been selected, the getCourseDetail() method defi ned in our session bean class
CourseSessionBean that will be built in the next section, will be called to retrieve fi ve pieces of detailed information for the selected course_id , and assign them to a List object
courseDetail .
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 defi ned 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 fi le, are defi ned in steps N , O , and P in this Java bean class. We will develop the codes to execute the data updating and delet- ing actions against our sample database later using these methods. The Back() method is used to return to the Selection.jsp page.
After fi nishing the code development for this bean, you may encounter some real - time 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 fi x 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 state- ment 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 fi nished import package block should match one that is shown in step A in Figure 8.157 . The modifi ed 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 fi eld. Select the JavaWebDBJSPOracle from the Package combo box, and check the Stateless radio button from the Session Type group. Your fi nished 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 fi le, perform the following operations to create the codes for this fi le, which is shown in Figure 8.160 .
c08.indd 746
c08.indd 746 7/20/2011 11:12:38 AM7/20/2011 11:12:38 AM
www.traintelco.com
Let ’ s have a closer look at this piece of codes to see how it works.
A. Add a new Session object as a property to this class since we need to create a new session object to perform the course data query using the Hibernate API later.
B. Right click on any space inside this code window and select the Insert Code from the pop - up menu. Then select the Add Business Method item to open the Add Business Method wizard. Enter getCourseID into the Name fi eld and click on the Browse button to fi nd the returning data type for this method. On the opened wizard, type List into the top fi eld and select List (java.util) from the bottom list. Then click on the OK button, and
OK button again to create this new method. Add a String argument fname to this method.
C. Inside the getCourseID() method, the getCurrentSession() method is executed to obtain the current opened session object, and assign it to our session property session we created at step A above.
D. Two local variables for this method, courseList , which is a java.util.List object, and a msgDlg , which is a JDialog object, are created fi rst. The courseList object is used to hold the returned queried result from the Course table, and the msgDlg is used to display the debug information as the project runs.
E. A combining HQL query that contains a subquery is created for this course_id query action. As you know, there is no faculty_name column available in the Course table, and the only relationship between each course ( course_id ) and the related faculty member is the faculty_id column in the Course table. Since the user ’ s input is the selected faculty name, therefore, we need to perform two queries to get all course_id taught by the selected faculty member, (1) perform a query to the Faculty table to get the related faculty_id based on the input faculty name selected by the user, and (2) perform another query to
Figure 8.159. The fi nished Name and Location wizard.
the Course table to get all course_id based on the faculty_id obtained from the fi rst query.
In order to simplify these two queries into one query, we need to use this combining query that contains a subquery that is used to perform the fi rst query to the Faculty table to obtain the desired faculty_id based on the input faculty_name . The only point to be noted for this HQL subquery is that this subquery must be surrounded by parentheses.
F. A try … catch block is used to perform the course information query from our Course table.
First, the beginTransaction() method is executed to create a new transaction object. Then
Figure 8.160. The codes for the session bean class CourseSessionBean.java.
package JavaWebDBJSPOracle;
import cse.entity.Faculty;
import cse.util.HibernateUtil;
import java.util.List;
import javax.ejb.Stateless;
import org.hibernate.Query;
import org.hibernate.Session;
@Stateless
public class CourseSessionBean { public Session session = null;
public List getCourseID(String fname) {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
List<Course> courseList = null;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
String query = "select c.courseId from Course c where c.facultyId like " +
"(select f.facultyId from Faculty as f where f.facultyName like '"+fname+"')";
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query c = session.createQuery (query);
courseList = (List<Course>) c.list();
} catch (Exception e) {
msgDlg.setMessage("Query is failed and no matched course_id found!");
msgDlg.setVisible(true);
e.printStackTrace();
return null;
}
return courseList;
}
public List<Object[]> getCourseDetail(String cid) {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
List<Object[]> courselist = null;
String strQuery = "select c.course, c.schedule, c.classroom, c.credit, c.enrollment " + "from Course c WHERE c.courseId = :courseid";
org.hibernate.Transaction tx = session.beginTransaction();
Query cQuery = session.createQuery(strQuery);
cQuery.setParameter("courseid", cid);
courselist = (List<Object[]>)cQuery.list();
return courselist;
} } A B C D E
F G H
I J K L M N O P Q
c08.indd 748
c08.indd 748 7/20/2011 11:12:38 AM7/20/2011 11:12:38 AM
www.traintelco.com
the createQuery() method is called to perform this data query. The combining HQL query statement works as an argument of this method and provides the query details.
G. The list() method is executed to perform this actual query operation. The queried result is returned and assigned to the local variable courseList .
H. The catch block is used to track and detect any possible exception during this query opera- tion, and display any error if any exception occurred. A null will be returned to the calling method if any exception occurred.
I. Finally, the queried result is returned to the calling method defi ned in our Java managed bean for further processing.
J. The getCourseDetail() method is defi ned here with the course_id as the argument.
The purpose of this method is to query fi ve pieces of detailed information from the Course entity based on the selected course_id and return the result to the JSF managed bean.
K. Inside the getCourseDetail () method, the getCurrentSession() method is executed to obtain the current opened session object and assign it to our session property session . Also, a new List instance courselist is created.
L. A HQL query is created with the courseid as a named dynamic parameter.
M. The beginTransaction() method is executed to create a new transaction object to help this course information query.
N. The query object cQuery is created by calling the createQuery() method.
O. The setParameter() method is executed to set up the named dynamic parameter
:courseid .
P. The list() method is executed to run this query to get fi ve pieces of detailed course infor- mation for the selected course_id , and the query result is assigned to the local List instance
courselist .
Q. The query result is returned to the JSF managed bean CourseBean for future process.
During the coding process, you may encounter some real - time compiling errors, which are indicated with some red underscores for the error sources. Most of these errors are related to the missed packages. To fi x these errors, just right click on any space in this code window, and select the Fix Imports item to open the Fix All Imports wizard.
The point to be noted is that you must select the correct packages for those real - time compiling error sources. For example, in this application, you need to select the following packages or classes for this fi le:
• org.hibernate.Query for the Query class • org.hibernate.Session for the Session class • java.util.List for the List collection class
Now we have completed the coding process for the course query operation with the Hibernate API. This piece of codes is only used for the course data query process, and the getCourseID() and getCourseDetail() methods will be called by our Java managed bean class CourseBean to execute these data query operations. We will add more methods and codes to perform other course data actions, such as data updating and deleting against our sample database later in the following sections.