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

Practical Database Programming With Java

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

858 Chapter 9 Developing Java Web Services to Access Databases

@WebMethod(operationName = "QueryCourse")

public ArrayList QueryCourse(@WebParam(name = "courseID") String courseID) {

//TODO write your implementation code here:

AArrayList<String> al = new ArrayList<String>();

Bal.clear();

CCourse result = courseFacade.getCourse(courseID);

Dal.add(0, result.getCourseId()); al.add(1, result.getCourse()); al.add(2, result.getCredit().toString()); al.add(3, result.getClassroom()); al.add(4, result.getSchedule());

al.add(5, result.getEnrollment().toString());

Ereturn al;

}

Figure 9.89. The codes for the Web service operation QueryCourse().

D.Six add() methods are used to add six pieces of detailed course information into the local ArrayList instance al. The point to be noted is that the data types of the credit and the enrollment columns in the Course table are numbers, therefore, a toString() method is needed to convert them to String before they can be added into the ArrayList object al.

E.The queried result is returned to the consuming project.

During the coding process, you may encounter some in-time compiling errors. The main reason for those errors is that some packages are missed. To fix these errors, just right click on any space inside this code window, and select the Fix Imports item to find and add those missed packages.

At this point, we have finished all coding process for the course details query. Now let’s build and test our Web service to test this course query function.

9.14.8.6 Build and Run the Web Service to Test the Course Query Function

Click on the Clean and Build Main Project button on the top of the window to build our Web service project. Then right click on our Web service application project WebServiceOracleApp and choose the Deploy item to deploy our Web service.

Enter the appropriate username and password to the Glassfish v3 server, such as admin and reback, which are used for this application, and click on the OK button to start the application server.

If everything is fine, expand the Web Services node under our Web service project and right click on our Web service target file WebServiceOracle, and choose the Test Web Service item to run our Web service project. The running status of our Web service is shown in Figure 9.90.

Enter a desired course_id, such as CSE-432, into the text field, and click on the queryCourse button to test this query function.The testing result is shown in Figure 9.91.

It can be found from Figure 9.91 that the detailed course information for the given course_id of CSE-432 has been retrieved and displayed at the bottom of this page, and our course details query via Web service is successful!

9.14 Build Java Web Service Projects to Access Oracle Databases 859

Figure 9.90. The running status of our Web service.

Figure 9.91. The running result of our Web operation QueryCourse().

860 Chapter 9 Developing Java Web Services to Access Databases

Next let’s handle creating and coding process for the third session bean method newCourse() and Web service operation InsertCourse() to insert a new course record into the Course table in our sample Oracle database.

9.14.8.7 Create and Build Session Bean Method newCourse()

Perform the following operations to create a new method newCourse() in our session bean class CourseFacade.java:

1.Open our Web service application project WebServiceOracleApp and double click on our session bean class CourseFacade.java from the Projects window to open it.

2.Right click on any place inside our session bean class body, choose the Insert Code item, and select the Add Business Method item to open the Add Business Method wizard.

3.Enter newCourse into the Name field and click on the Browse button that is next to the

Return Type combo box. On the opened Find Type wizard, type boolean into the top field and select the Boolean (java.lang) from the list and click on the OK button.

4.Recall that in Chapter 2, when we built our sample database, the Course table contains seven columns. Therefore, in order to insert a new course record, we need to pass seven new values for those seven columns. We need to use an ArrayList object to store those param-

eters. Click on the Add button and enter cdata into the Name parameter field. Then click on the drop-down arrow of the Type combo box, and select the Choose item to open the Find Type wizard. Type arraylist into the top field and select the ArrayList (java.util) data type, and click on the OK button to select an ArrayList as the data type for the input parameter. Your finished Add Business Method wizard should match the one that is shown in Figure 9.92. Click on the OK button to complete this business method creation process.

Now let’s develop the codes for this method.

Click on the Source button on the top of this window to open the code window of our session bean class CourseFacade.java. Enter the codes that are shown in Figure 9.93 into this new method newCourse(). The newly added codes have been highlighted in bold.

Figure 9.92. The finished Add Business Method wizard.

9.14 Build Java Web Service Projects to Access Oracle Databases 861

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

}

public Boolean newCourse(ArrayList cdata) {

ACourse c = new Course();

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

fQuery.setParameter("FacultyName", cdata.get(6).toString()); String fid = fQuery.getSingleResult().toString();

Cc.setCourseId(cdata.get(0).toString()); c.setCourse(cdata.get(1).toString());

Dc.setCredit(new BigInteger(cdata.get(2).toString())); c.setClassroom(cdata.get(3).toString()); c.setSchedule(cdata.get(4).toString());

Ec.setEnrollment(new BigInteger(cdata.get(5).toString()));

Fc.setFacultyId(new Faculty(fid));

Gcreate(c);

Hreturn true;

}

Figure 9.93. The codes for the method newCourse().

The codes for this method is a little complicated since we utilized a built-in method create() that is created and added into this session bean class automatically when this session bean is created.

As you know, when we built our Course table in Chapter 2, there is no faculty_name column available in the Course table, and the only relationship between each course_id and each faculty member is the faculty_id column in the Course table. This is a many- to-one relationship between the course_id and the faculty_id in this table, which means that many courses (course_id) can be taught by a single faculty (faculty_id). However, in the Faculty table, there is a one-to-one relationship between each faculty_name and each faculty_id column.

Therefore, in order to insert a new course record into the Course table based on a selected faculty member, exactly the faculty_name, we need to perform two queries from two tables.

First, we need to perform a query to the Faculty table to get a matched faculty_id based on the selected faculty member (faculty_name).

Then we need to perform another action to the Course table to insert a new course record including the faculty_id that is obtained from the first query.

Based on this discussion, let’s have a closer look at this piece of codes to see how it works.

A.First, a new Course object c is created since we want to call a built-in method create() to perform this new course insertion, and that method needs a Course object as the argument.

B.Then the first query is executed to get a matched faculty_id based on the selected faculty_ name, which is the sixth input parameter stored in our ArrayList instance cdata. The queried faculty_id is returned and assigned to a local variable fid.

862Chapter 9 Developing Java Web Services to Access Databases

C.Seven setter methods are executed to pick up seven input parameters that represent a new course record and set each of them to the associated column in the new Course object c.

D.Points to be noted are steps D and E. Since the data types for the 2nd and 5th parameters, credit and enrollment, in the input ArrayList instance are BigInteger, we must convert both data into that data type by creating a new instance of BigInteger class.

F.Since the setFacultyId() method needs a Faculty class as the argument data type, we need to create a new Faculty instance with the queried faculty_id as the argument to meet this requirement.

G.The built-in method create() is called with the built Course instance c as the argument. The function of the create() method is to create and insert a new course record into the Course table. No query result is returned for this method.

H.A true is returned to the associated Web operation to indicate that this data insertion is successful.

During the coding process, you may encounter some real-time compiling errors. Most of these errors are introduced by missing some packages that contain classes or components used in this file. To fix these errors, just right click on this code window and select the Fix Imports item to load and import those missed packages to the top of this code window.

To save this piece of codes, click on the Clean and Build Main Project button on the top to build our project.

Next, let’s create and build our third Web service operation InsertCourse() to call this session bean method newCourse() to insert a new course record into our Course table.

9.14.8.8 Create and Build Web Service Operation InsertCourse()

Perform the following operations to add this operation into our Web service:

1.Launch NetBeans IDE and open our Web service project WebServiceOracleApp, and double click on our Web service main class file WebServiceOracle.java from the Projects window to open it.

2.Click on the Design button on the top of the window to open the Design View of our Web service project WebServiceOracle.

3.Click on the Add Operation button to open the Add Operation wizard.

4.Enter InsertCourse into the Name field and click on the Browse button that is next to the

Return Type combo box. Type boolean into the Type Name field and select the item Boolean (java.lang) from the list, and click on the OK button.

5.Click on the Add button and enter cdata into the Name parameter field. Then click on the drop-down arrow of the Type combo box, and select the Choose item to open the Find Type wizard. Type arraylist into the top field and select the ArrayList (java.util) data type, and click on the OK button to select an ArrayList as the data type for the input parameter.

Your finished Add Operation wizard should match the one that is shown in Figure 9.94. Click on the OK button to complete this new operation creation process.

Click on the Source button on the top of this window to open the code window of our Web service project. Let’s perform the coding for this newly added operation.

9.14 Build Java Web Service Projects to Access Oracle Databases 863

Figure 9.94. The complete Add Operation wizard.

@WebMethod(operationName = "InsertCourse")

public Boolean InsertCourse(@WebParam(name = "cdata") ArrayList cdata) {

//TODO write your implementation code here:

ABoolean insert = false;

Binsert = courseFacade.newCourse(cdata);

Creturn insert;

}

Figure 9.95. The codes for the Web service operation InsertCourse().

On the opened code window, enter the codes that are shown in Figure 9.95 into this newly added operation InsertCourse().

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

A.A local Boolean variable insert is created and initialized to false. This local variable is used to hold the running result of execution of the session bean method newCourse() that performs a new course insertion action to the Course table in our sample database.

B.The session bean method newCourse() is called to perform a new course insertion action via Java persistence API and entity classes.

C.The running status of the session bean method is returned to the consuming project.

At this point, we have finished all coding processes for the course insertion action. Now we can build and deploy our Web service to save these codes.

9.14.8.9 Build and Deploy the Web Service Project

Perform the following operations to build and deploy our Web service project:

1.Click on the Clean and Build Main Project button to build our Web service.

2.Right click on our Web application WebServiceOracleApp and select the Deploy item to deploy our Web service. If everything is fine, a successful deployment result should be displayed, as shown in Figure 9.96.

864 Chapter 9 Developing Java Web Services to Access Databases

Figure 9.96. The deployment result of our Web service project.

A problem arises when testing this Web service project using the tester page, which is the input parameter array cdata. As we know, the cdata has a data type of ArrayList, and it needs to (1) create an ArrayList instance, and then (2) assign a group of new course information to that ArrayList object to call this Web service operation InsertCourse() to perform the course data insertion. However, it is difficult to do those two operations manually by using this tester page. Therefore, we need to create some Web client projects to consume and test this Web service project in the later sections.

Next, let’s discuss how to update a course record using the Web service operations. As we discussed in the previous sections, the key point to perform a course data updating 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 because of the complexity in cascaded updating relationships we built in Chapter 2 when we create our sample database. Therefore, in this section, we will concentrate on the updating a course

record based on an existing course_id.

As we discussed in Section 9.14.6, to update an existing course record in the Course table, we need to build a Web service operation UpdateCourse() and a session bean method setCourse(), respectively. First, let’s take care of creating the session bean method setCourse() in our session bean class CourseFacade.java.

9.14.8.10 Create and Build Session Bean Method setCourse()

Perform the following operations to create a new method setCourse() in our session bean class CourseFacade.java:

1.Open our Web service application project WebServiceOracleApp and double click on our session bean class CourseFacade.java from the Projects window to open it.

2.Right click on any place inside our session bean class body, and choose the Insert Code item and select the Add Business Method item to open the Add Business Method wizard.

3.Enter setCourse into the Name field and click on the Browse button that is next to the

Return Type combo box. On the opened Find Type wizard, type boolean into the top field and select the Boolean (java.lang) from the list and click on the OK button.

9.14 Build Java Web Service Projects to Access Oracle Databases 865

4.Recall that in Chapter 2, when we built our sample database, the Course table contains seven columns. Therefore, in order to update an existing course record based on a selected course_id, we need to pass six updated course columns’ values with the seventh value that is the selected course_id. We like to use an ArrayList object to store those parameters. Click on the Add button and enter cdata into the Name parameter field. Then click on the drop-down arrow of the Type combo box, select the Choose item to open the Find Type wizard. Type arraylist into the top field and select the ArrayList (java.util) data type, and click on the OK button to select an ArrayList as the data type for the input parameter.

Your finished Add Business Method wizard should match the one that is shown in Figure 9.97. Click on the OK button to complete this business method creation process.

Now let’s develop the codes for this method.

Click on the Source button on the top of this window to open the code window of our session bean class CourseFacade.java. Enter the codes that are shown in Figure 9.98 into this new method setCourse(). The newly added codes have been highlighted in bold.

Figure 9.97. The finished Add Business Method wizard.

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

}

public Boolean setCourse(ArrayList cdata) {

ACourse c = new Course();

BString f_query = "SELECT f.facultyId FROM Faculty f WHERE f.facultyName = :FacultyName"; Query fQuery = em.createQuery(f_query).setParameter("FacultyName", cdata.get(6).toString());

Cc.setCourseId(cdata.get(0).toString()); c.setCourse(cdata.get(1).toString());

Dc.setCredit(new BigInteger(cdata.get(2).toString())); c.setClassroom(cdata.get(3).toString()); c.setSchedule(cdata.get(4).toString());

Ec.setEnrollment(new BigInteger(cdata.get(5).toString()));

Fc.setFacultyId(new Faculty(fQuery.getSingleResult().toString()));

Gedit(c);

Hreturn true;

}

Figure 9.98. The codes for the method setCourse().

866 Chapter 9 Developing Java Web Services to Access Databases

The codes for this method is similar to those we built for the newCourse() method, and we also utilized a built-in method edit() that is created and added into this session bean class automatically when this session bean is created.

Similar to our discussions in Section 9.14.8.7, in order to update an existing course record in the Course table based on the existing course_id and a selected faculty member, exactly the faculty_name, we need to perform two queries from two tables.

First, we need to perform a query to the Faculty table to get a matched faculty_id based on the selected faculty member (faculty_name).

Then, we need to perform another action to the Course table to update an existing course record including the faculty_id that is obtained from the first query.

Based on this discussion, let’s have a closer look at the codes shown in Figure 9.93 to see how it works.

A.First, a new Course object c is created, since we want to call a built-in method edit() to perform this course data updating, and that method needs a Course object as the argument.

B.Then, the first query is executed to get a matched faculty_id based on the selected faculty_name, which is the sixth input parameter stored in our ArrayList instance cdata. A combination command is used to perform the named parameter setup operation.

C.Seven setter methods are executed to pick up seven input parameters that represent an updated course record and set each of them to the associated column in the new Course object c.

D.Points to be noted are steps D and E. Since the data types for the 2nd and 5th parameters, credit and enrollment, in the input ArrayList instance are BigInteger, we must convert both data into that data type by creating a new instance of BigInteger class.

F.Since the setFacultyId() method needs a Faculty class as the argument data type, we need to create a new Faculty instance with the queried faculty_id as the argument to meet this requirement. Here, we did not assign the first query result to a local variable as we did in the newCourse() method; instead we directly use the query result of the first query as an argument for this new Faculty instance.

G.The built-in method edit() is called with the built Course instance c as the argument. The function of the edit() method is to update an existing record and merge it to that original record in the Course table. No query result is returned for this method.

H.A true is returned to the associated Web operation to indicate that this data updating is successful.

During the coding process, you may encounter some real-time compiling errors. Most of these errors are introduced by missing some packages that contain classes or components used in this file. To fix these errors, just right click on this code window and select the Fix Imports item to load and import those missed packages to the top of this code window.

To save this piece of codes, click on the Clean and Build Main Project button on the top to build our project.

Next, let’s create and build our fourth Web service operation UpdateCourse() to call this session bean method setCourse() to update an existing course record in our Course table.

9.14 Build Java Web Service Projects to Access Oracle Databases 867

9.14.8.11 Create and Build Web Service Operation UpdateCourse()

Perform the following operations to add this new operation into our Web service:

1.Launch NetBeans IDE and open our Web service project WebServiceOracleApp, and double click on our Web service main class file WebServiceOracle.java from the Projects window to open it.

2.Click on the Design button on the top of the window to open the Design View of our Web service project WebServiceOracle.

3.Click on the Add Operation button to open the Add Operation wizard.

4.Enter UpdateCourse into the Name field and click on the Browse button that is next to

the Return Type combo box. Type boolean into the Type Name field and select the item Boolean (java.lang) from the list, and click on the OK button.

5.Click on the Add button and enter cdata into the Name parameter field. Then click on the drop-down arrow of the Type combo box, and select the Choose item to open the Find Type wizard. Type arraylist into the top field and select the ArrayList (java.util) data type, and click on the OK button to select an ArrayList as the data type for the input parameter.

Your finished Add Operation wizard should match the one that is shown in Figure 9.99. Click on the OK button to complete this new operation creation process.

Click on the Source button on the top of this window to open the code window of our Web service project. Let’s perform the coding for this newly added operation.

On the opened code window, enter the codes that are shown in Figure 9.100 into this newly added operation UpdateCourse().

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

A.A local Boolean variable update is created and initialized to false. This local variable is used to hold the running result of execution of the session bean method setCourse() that performs a course record updating action to the Course table in our sample database.

B.The session bean method setCourse() is called to perform a course record updating action via Java persistence API and entity classes.

C.The running status of the session bean method is returned to the consuming project.

Figure 9.99. The complete Add Operation wizard.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]