Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
788
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

8.5 Build Java Web Project to Access SQL Server Database 677

Figure 8.99. The Entity Classes wizard.

Figure 8.100. The Generated Session Beans wizard.

on the Add button to add them to the Selected Entity Classes list, as shown in Figure 8.99. Make sure to check the Include Referenced Classes checkbox and click on the Next button to continue.

5. In the opened Generated Session Beans wizard, which is shown in Figure 8.100, click on the Finish button to complete this creating new session beans for entity classes process.

The reason we only selected two entity classes, JavaWebDBJSPSQL.Course and

JavaWebDBJSPSQL.Faculty, in step 4 above for this session bean is that we only need two tables, Course and Faculty, in our sample database to perform this course query operation. As you know, no faculty_name column is available in the Course table, and all course information is identified by using the faculty_id column in the Course table.

678 Chapter 8 Developing Java Web Applications to Access Databases

In order to get the faculty_id based on the selected faculty_name by the user, one needs to perform a query from the Faculty table to do that first. Therefore, we need these two tables to perform this course information query job.

Now, let’s build the codes for this session bean class to perform data actions against our sample database using Java Persistence API technique.

Open the code window of this new Session Beans For Entity Class CourseFacade from the Projects window and enter the codes that are shown in Figure 8.101 into this class. The new added codes have been highlighted in bold.

Let’s have a close look at these newly added codes to see how they work.

A.The javax.persistence.Query class is imported first since we need to use this component to perform the course information query in this class. All other packages are imported by the NetBeans IDE when this session class is created.

B.A user-defined property courseList is created since we need to use this property to store and return the queried result, which is a List component containing the queried course_id for the selected faculty member. The msgDlg is a JDialog object, and it is used to display the testing and debug information when this project is tested and debugged later.

C.The getCourseID() method is defined here, and this method is used to query all course_id taught by the selected faculty member by the user as the project runs. To perform this query, two queries needs to be performed. First, the faculty_id needs to be queried from the Faculty table based on the selected faculty_name, and then the course_id needs to be queried based on the faculty_id from the Course table. Here, a Java persistence query is created by using the createQuery() method to perform the first query. A named dynamic parameter :FacultyName is used for this query.

D.Steps D, E and F are used to set the named dynamic parameter :FacultyName for the first Java persistence query. First, a new Faculty instance fFaculty is created based on the Faculty entity class. Then the setFacultyName() method is executed with the selected faculty_name as the argument to make sure that the newly created Faculty instance has the selected faculty_name as the default faculty name. Finally, the setParameter() method is executed to set up the dynamic named parameter :FacultyName with the default faculty_name that is obtained by calling the getFacultyName() method as the argument. The reason we used these three steps to set up this named dynamic parameter is that the data type of the second argument for the setParameter() method is Object, not String. Therefore, we need to use a new Faculty instance to do that setup.

G.Similar to steps D, E, and F, we create another new Faculty instance cFaculty with the queried faculty_id as the argument to make it as an object for the setParameter() method in the second query. The getSingleResult() method that works as an argument for this newly created Faculty instance is used to execute the first query to get the faculty_id based on the faculty_name.

H.The second Java persistence query is created with the :facultyID as a named dynamic parameter.

I.The setParameter() method is executed to set up the named dynamic parameter :facultyID. The second argument of this method is a Faculty instance cFaculty that can be considered as an object, and it is created with the queried faculty_id in step G. This makes sure that the queried faculty_id will be set to that named dynamic parameter

:facultyID.

J.The getResultList() method is executed to perform the second query to get all course_id, and the returned result is assigned to the bean’s property courseList.

8.5 Build Java Web Project to Access SQL Server Database 679

package JavaWebDBJSPSQLPackage;

import java.util.List; import javax.ejb.Stateless;

import javax.persistence.EntityManager; import javax.persistence.PersistenceContext;

Aimport javax.persistence.Query;

@Stateless

public class CourseFacade {

@PersistenceContext(unitName = "JavaWebDBJSPSQLPU") private EntityManager em;

Bprivate List courseList;

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);

public void create(Course course) { em.persist(course);

}

public void edit(Course course) { em.merge(course);

}

public void remove(Course course) { em.remove(em.merge(course));

}

public Course find(Object id) { return em.find(Course.class, id);

}

public List<Course> findAll() {

return em.createQuery("select object(o) from Course as o").getResultList();

}

public List<Course> findRange(int[] range) {

Query q = em.createQuery("select object(o) from Course as o"); q.setMaxResults(range[1] - range[0]); q.setFirstResult(range[0]);

return q.getResultList();

}

public int count() {

return ((Long) em.createQuery("select count(o) from Course as o").getSingleResult()).intValue();

}

Cpublic List getCourseID(String fname) {

Query fQuery = em.createQuery("SELECT f.facultyId FROM Faculty f " + "WHERE f.facultyName= :FacultyName");

DFaculty fFaculty = new Faculty();

EfFaculty.setFacultyName(fname);

FfQuery.setParameter("FacultyName", fFaculty.getFacultyName());

GFaculty cFaculty = new Faculty((String)fQuery.getSingleResult());

HQuery cQuery = em.createQuery("SELECT c.courseId FROM Course c WHERE c.facultyId = :facultyID");

IcQuery.setParameter("facultyID", cFaculty);

Jthis.courseList = cQuery.getResultList();

Kreturn courseList;

}

Lpublic List<Object[]> getCourseDetail(String cid) { List<Object[]> courselist = null;

MString strQuery = "SELECT c.course, c.schedule, c.classroom, c.credit, c.enrollment " +

"FROM Course c WHERE c.courseId = :courseid";

NQuery cQuery = em.createQuery(strQuery);

OcQuery.setParameter("courseid", cid);

Pcourselist = cQuery.getResultList();

Qreturn courselist;

}

}

Figure 8.101. The codes for the session bean CourseFacade.

680Chapter 8 Developing Java Web Applications to Access Databases

K.The queried result is returned to the JSF managed bean CourseBean for further process.

L.The getCourseDetail() method is defined here with the course_id as the argument. The purpose of this method is to query five pieces of detailed information from the Course entity based on the selected course_id, and return the result to the JSF managed bean. First, a new List instance courselist is created.

M.A Java persistence query is created with the courseid as a named dynamic parameter.

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 getResultList() method is executed to run this query to get five pieces of detailed information 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.

Those codes that have not been highlighted in bold in this class are created by the NetBeans IDE automatically when this session bean is created.

If you encounter some real-time compiling errors for some codes in this window, right click on any place in this window and select the Fix Imports item to try to solve those errors. A typical error you may encounter is that you missed the java.util.List class in the import section.

Now, let’s set up a calling relationship between the JSF managed bean CourseBean and the session bean CourseFacade.

8.5.6.4 Set Up Calling Relationship between the JSF Bean and the Session Bean

Perform the following operations to set up this calling relationship between the JSF managed bean CourseBean and the session bean CourseFacade:

1.Open the code window of the JSF managed bean class CourseBean.

2.Right click on this code window and select the Insert Code item from the pop-up menu.

3.Click on the Call Enterprise Bean item from the opened list.

4. On the opened Call Enterprise Bean wizard, as shown in Figure 8.102, select our session bean class CourseFacade from the list.

5.Keep the No Interface radio button checked since we do not need any interface, and we have built our Web page CoursePage as the interface for this project.

6.Click on the OK button to complete this setup.

Immediately, you can find that two coding lines, as shown below, have been added into the code window of our JSF managed bean class CourseBean. Exactly they are located under the class header:

@EJB

private CourseFacade courseFacade;

The @EJB is an injected source and added by the Java Enterprise Bean engine, and the new instance courseFacade is created as a new property in our JSF managed bean class CourseBean.

8.5 Build Java Web Project to Access SQL Server Database 681

Figure 8.102. The finished Call Enterprise Bean wizard.

Figure 8.103. The running stage of the CoursePage.

At this point, we have finished all coding jobs for our project. Now let’s build and run our project to test the codes we built in the previous sections for this project.

8.5.6.5 Build and Run the Project to Test the Course Information Query Functions

Now click on the Clean and Build Main Project button to build our project. If everything is fine, right click on our CoursePage.jsp from the Projects window and select the Run File item from the popup menu to run this page. The running page is shown in Figure 8.103.

Enter a faculty name, such as Jenney King, into the Faculty Name field, and click on the Select button to retrieve all courses, exactly all course_id, taught by the selected

682 Chapter 8 Developing Java Web Applications to Access Databases

Figure 8.104. The queried results of the CoursePage.

faculty member.All four courses taught by the faculty member Jenney King are retrieved and displayed in the course listbox, as shown in Figure 8.104.

Click one course_id, such as CSE-432, from the course listbox, and click on the Details button to try to query and retrieve the details for that course. All five pieces of detailed information related to the selected course_id are displayed in five fields, as shown in Figure 8.104.

Our course information query using JSF pages and Java bean is successful.

Click on the Close button that is located at the upper-right corner of this page to close this page and project.

Next, we will discuss how to update and delete a record from the Course table in our sample database.

8.5.7 Update Records from the Course Table Using JavaServer Faces and Java Beans

In this section, we will discuss how to update a record for the Course table in our sample database using JSF page and Java beans techniques.

We will use the Update button on the CoursePage page to perform this data updating operation.

Recall that in Section 8.5.6.1, the Update button in the JSF page CoursePage is bound to the Update() method defined in the Java managed bean class CourseBean via the action attribute of that button. Now we can use this bound relationship to perform the course information updating operation against our sample database.

The key point to be noted is that in most real applications, all pieces of course information should be updated except the course_id, since it is much easier to insert a new course record with a new course_id than updating a record with an updated course_id.

8.5 Build Java Web Project to Access SQL Server Database 683

public Boolean Update() {

AString[] newCourse = {null, null, null, null, null, null};

BnewCourse[0] = selectedItem; newCourse[1] = getCourseName(); newCourse[2] = getSchedule(); newCourse[3] = getClassroom(); newCourse[4] = getCredit(); newCourse[5] = getEnrollment();

CcourseFacade.UpdateCourse(newCourse);

Dreturn null;

}

Figure 8.105. The codes for the Update() method.

Therefore, in this section, we will concentrate on the updating a course record based on an existing course_id.

As we did for the course information query in the last section, we still want to use the managed bean CourseBean as an intermediate-level controller to call a business method UpdateCourse() defined in the session bean CourseFacade to perform this course record updating.

First, let’s create the codes for the Update() method in the JSF managed bean CourseBean to call the UpdateCourse() method that is defined in the session bean CourseFacade class and will be developed in the next section to do this course updating.

8.5.7.1 Create Codes for the Update() Method in the JSF Managed Bean

Open our project JavaWebDBJSPSQL from the Projects window and our managed bean class CourseBean. Browse to the Update() method and enter the codes that are shown in Figure 8.105 into this method.

Let’s have a closer look at this piece of codes to see how it works.

A.In order to perform a course record updating, we need to collect and pass six pieces of updated course information into the UpdateCourse() method defined in the session bean CourseFacade to access the database to do this updating. So a string array newCourse[] that is used to hold those pieces of information with six elements is created first.

B.Then six pieces of collected course updating information are assigned to each element in the newCourse[] array using the getter methods. The point to be noted is the data process performed between the JSF page CoursePage and the JSF managed bean CourseBean. In fact, before the Update button in the CoursePage can be clicked by the user, all six pieces of course updating information should have been entered into six inputText field. Recall that the value attributes of these six inputText fields have been bound to the associated properties defined in the CourseBean class. The true story is that as the user clicks the Update button, all six pieces of course updating information stored in the six inputText fields will be submitted to the JSF managed bean CourseBean and assigned to the associated properties defined in that bean class. To get those properties, we need to use the associated getter method to do that and assign each of them to an element in the string

array newCourse[]. The selectedItem property contains the course_id selected by the user from the <h:selectOneListbox> tag in the CoursePage.

684 Chapter 8 Developing Java Web Applications to Access Databases

public void UpdateCourse(String[] nCourse) {

A String query = "UPDATE Course c SET c.course=?1, c.schedule=?2, c.classroom=?3, " + "c.credit=?4, c.enrollment=?5 WHERE c.courseId=:CourseID";

Bem.clear();

CQuery cQuery = em.createQuery(query);

DcQuery.setParameter(1, nCourse[1]); cQuery.setParameter(2, nCourse[2]); cQuery.setParameter(3, nCourse[3]); cQuery.setParameter(4, Integer.parseInt(nCourse[4])); cQuery.setParameter(5, Integer.parseInt(nCourse[5])); cQuery.setParameter("CourseID", nCourse[0]);

EcQuery.executeUpdate();

}

Figure 8.106. The codes for the UpdateCourse() method.

C.The UpdateCourse() method defined in the session bean class CourseFacade is called with the newCourse[] array as the argument to perform this data updating action.

D.The returning value is not important to us since the data updating action has been performed by executing the UpdateCourse() method. To simplify the execution of this

method, we did not use any returned value to check and confirm this action. You can use a returned integer or Boolean to do this confirmation if you like.

Next, let’s develop the codes for the UpdateCourse() method in the session bean class to access our sample database to perform this data updating action.

8.5.7.2 Create Codes for the UpdateCourse() Method in the Session Bean

Open the code window of the session bean class CourseFacade and create a new method UpdateCourse() and enter the codes that are shown in Figure 8.106 into this method.

Let’s have a closer look at this piece of codes to see how it works.

A.A dynamic JPA query statement with the positional parameters and named parameter is created first. The five pieces of course updating information are arranged in a sequence order with the attached number as the indicator, and the last parameter is a named parameter CourseID that works as a query criterion.

B.The EntityManager is first cleaned up to make this data updating ready.

C.The dynamic query object is created by calling the createQuery() method.

D.Five pieces of course updating information, including the query criterion course_id, are assigned to the associated positional and named parameters, and one by one defined in the query statement. Two points to be noted for these assignments are: first, the order of this assignment must be identical with the order of positional parameters defined in the query statement we created in step A. Second, the data types for parameters 4 and 5, or credit and enrollment, are both INTEGER (SMALLINT for credit and INTEGER for enrollment) when we created the Course table in our sample database. Therefore, you must use the parseInt() method defined in the Integer class to convert these two parameters from String to Integer,respectively,and then assign them to those dynamic parameters.Otherwise, you may encounter a compiling error during building the project later.

8.5 Build Java Web Project to Access SQL Server Database 685

Figure 8.107. The running status of the CoursePage.

E.Finally the executeUpdate() method is executed to perform this data updating action. One point to be noted is that no Transaction object should be used for this data manipulation since JPA can handle this automatically.

At this point, we have completed all coding jobs for the course data updating operation. Now, let’s build and run our project to test this data updating function.

Click on the Clean and Build Main Project button to build our project. If everything is fine, right click on our CoursePage.jsp from the Projects window and select the Run File item from the pop-up menu to run this page.

Enter a faculty name, such as Jenney King, into the Faculty Name field, and click on the Select button to retrieve and display all courses taught by this faculty in the CourseList box. Then select one course_id, such as CSE-432, from the CourseList box, and click on the Details button to get the details for this course. The running result is shown in Figure 8.107.

To update this course, enter the updating information shown in Figure 8.108 into the five inputText fields.

Click on the Update button to try to update this course.

To confirm this data updating action, two methods can be used: first, you can open the Course table from the NetBeans IDE environment to do this confirmation. To do that, open the Services window and expand to our Course table, right click on the Course table, and select the View Data item from the pop-up menu to open this table. Browse down to the course CSE-432, and you can find that the course has been updated, as shown in Figure 8.109.

The second way to confirm this updating action is to use the Details button to try to retrieve the details of this updated course. To do that, first select another course_id from the CourseList box and click on the Details button to get details for that course. Then select the CSE-432 from the list and click on the Details button again, You can find that the course CSE-432 has been updated based on the retrieved and displayed details for this course.

686 Chapter 8 Developing Java Web Applications to Access Databases

Figure 8.108. The updating information for the course CSE-432.

Figure 8.109. The updated course CSE-432.

Before closing this project, it is highly recommended to recover this updated course. To do that recovery, just enter the following original details for the course CSE-432 into the five inputText fields, and then click on the Update button to complete this data recovery.

CourseID:

CSE-432

Course Name:

Analog Circuit Designs

Schedule:

M-W-F: 2:00–2:55 PM

Classroom:

TC-309

Credits:

3

Enrollment:

18