Create and Build the Session Bean Methods and Web

Một phần của tài liệu practical database aprogramming with java (Trang 722 - 746)

JAVA RUNTIME OBJECTS METHOD

9.14 BUILD JAVA WEB SERVICE PROJECTS TO ACCESS

9.14.8 Create and Build the Session Bean Methods and Web

Let ’ s start to create each session bean method and develop the codes for each of them.

First, let ’ s start from the getCourseID() method.

Recall that when we built our sample database in Chapter 2 , especially when we built the Course table, there is no faculty_name column available in the Course table, and the

c09.indd 849

c09.indd 849 7/20/2011 11:12:52 AM7/20/2011 11:12:52 AM

www.traintelco.com

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 query all courses, exactly all course_id , taught by the 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 query to the Course table to get all course_id taught by the selected faculty_id that is obtained from the fi rst query.

Based on this discussion, now let ’ s perform the following operations to add a new method getCourseID() into our session bean CourseFacade.java to perform this

course_id query:

9.14.8.1 Create and Build Session Bean Method getCourseID()

Perform the following operations to create a new method getCourseID() 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, then choose the Insert Code item and select the Add Business Method item to open the Add Business Method wizard.

3. Enter getCourseID into the Name fi eld and click on the Browse button that is next to the Return Type combo box. On the opened Find Type wizard, type list into the top fi eld and select the List (java.util) from the list and click on the OK button.

4. Click on the Add button to add one argument for this method. Enter fname into the Name column and keep the default data type java.lang.String unchanged. Your fi nished Add Business Method wizard should match the one that is shown in Figure 9.80 . 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.81 into this code window and the new method getCourseID() .

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

A. First, an MsgDialog instance msgDlg is created since we need to use this object to track and display some debugging information as we test our Web service later.

B. A List instance courseList is created and initialized, and we need to use it to hold the query result, which are all course_id taught by the selected faculty member.

C. Two queries should be performed to get all course_id taught by the selected faculty member, (1) query to the Faculty table to get a matched faculty_id based on the selected faculty name, and (2) query to the Course table to get all course_id based on the faculty_

id obtained from the fi rst query. The query statement of the fi rst query is created at this step.

D. The createQuery() method is executed to create the fi rst query object fQuery based on the query statement created in step C .

E. Since the query statement in the fi rst query contains a named dynamic parameter

FacultyName , the setParameter() method is executed to set up this parameter with an actual value fname , which is the input argument of this method.

F. Then the getSingleResult() method is called to perform the fi rst query to get a matched faculty_id and return it to a local variable fi d .

G. The second query statement is created with a named dynamic parameter FacultyID . H. The createQuery() method is executed to create the second query object cQuery based

on the query statement created in step G .

Figure 9.80. The fi nished Add Business Method wizard.

Figure 9.81. The codes for the method getCourseID().

A

B C D E F G H I J K L

@Stateless

public class CourseFacade {

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

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

………

public List getCourseID(String fname) { List courseList = null;

String f_query = "SELECT f.facultyId FROM Faculty f WHERE f.facultyName = :FacultyName";

Query fQuery = em.createQuery(f_query);

fQuery.setParameter("FacultyName", fname);

String fid = fQuery.getSingleResult().toString();

String c_query = "SELECT c.courseId FROM Course c WHERE c.facultyId = :FacultyID";

Query cQuery = em.createQuery(c_query);

Faculty f = new Faculty(fid);

cQuery.setParameter("FacultyID", f);

courseList = cQuery.getResultList();

return courseList;

} }

c09.indd 851

c09.indd 851 7/20/2011 11:12:52 AM7/20/2011 11:12:52 AM

www.traintelco.com

I. A tricking issue arises in the next step. As we know, the data type for the second argument in the setParameter() method should be an Object. However, the data type for the queried

faculty_id , or fi d , from the fi rst query is a String. In order to enable the setParameter() method to be executed correctly, we must create a new Faculty object with the queried

faculty_id as the argument in this step.

J. Then the setParameter() method is executed to set up this correct faculty_id that is involved in the newly created Faculty object in step I .

K. The getResultList() method is executed to perform the second query and return the query result to the local variable courseList we created in step B.

L. Finally, the query result is returned to the calling method or operation.

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 compo- nents used in this fi le. To fi x 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 fi rst Web service operation QueryCourseID() to call this session bean method getCourseID() to query all course_id taught by the selected faculty.

9.14.8.2 Create and Build Web Service Operation QueryCourseID()

Now let ’ s begin the coding process for operations in our Web service project. First let ’ s create the fi rst operation in our Web service to query all course_id from the Course table.

Perform the following operations to add a new operation QueryCourseID() into our Web service project to perform this course_id query:

1. Double click on our Web service project 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 QueryCourseID into the Name fi eld and click on the Browse button that is next to the Return Type combo box. Type arraylist into the Type Name fi eld and select the item ArrayList (java.util) from the list, and click on the OK button.

5. Click on the Add button and enter fname into the Name parameter fi eld. Keep the default type java.lang.String unchanged and click on the OK button to complete this new opera- tion creation process.

Your fi nished Add Operation wizard should match the one that is shown in Figure 9.82 .

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.83 into this code window and this newly added operation.

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

A. First, a class - level variable msgDlg is created. This variable is used to track and display the debug information when this Web service project is tested later.

B. An ArrayList instance al and a List instance courseList are created. The fi rst variable is an array list instance used to collect and store our query result, and return to the consum- ing project. The second variable is used to hold and store the query result from the execu- tion of the session bean method getCourseID() .

C. The session bean method getCourseID() is called to query all course_id taught by the selected faculty member fname that works as an argument of that method. The query result is returned and assigned to the local variable courseList .

D. A for loop is used to pick up each queried course_id and add it into the ArrayList instance

al . The reason we used an ArrayList, not a List instance, as the returned object is that the former is a concrete class but the latter is an abstract class, and a runtime exception may be encountered if an abstract class is used as a returned object to the calling method.

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

Figure 9.82. The fi nished Add Operation wizard.

Figure 9.83. The codes for the Web service operation QueryCourseID().

A

B C D

E

@WebService()

public class WebServiceOracle { @EJB

private CourseFacade courseFacade;

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

@WebMethod(operationName = "QueryCourseID")

public ArrayList QueryCourseID(@WebParam(name = "fname") String fname) {

//TODO write your implementation code here:

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

List courseList = null;

courseList = courseFacade.getCourseID(fname);

for (int col = 0; col < courseList.size(); col++) { al.add(courseList.get(col).toString());

} return al;

} }

c09.indd 853

c09.indd 853 7/20/2011 11:12:53 AM7/20/2011 11:12:53 AM

www.traintelco.com

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 fi x these errors, just right click on any space inside this code window, and select the Fix Imports item to fi nd and add those missed packages.

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

9.14.8.3 Build and Run the Web Service to Test the course_id 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 Glassfi sh 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 fi ne, expand the Web Services node under our Web service project and right click on our Web service target fi le 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.84 .

Enter a desired faculty name, such as Jenney King , into the text fi eld, and click on the queryCourseID button to test this query function. The testing result is shown in Figure 9.85 .

It can be found from Figure 9.85 that all course_id taught by the selected faculty member Jenney King have been retrieved and displayed at the bottom of this page, and our course_id query via Web service is successful!

Next, let ’ s handle creating and coding process for the second session bean method

getCourse() and Web service operation QueryCourse() to query details for a selected

course_id .

Figure 9.84. The running status of our Web service operation QueryCourseID().

9.14.8.4 Create and Build Session Bean Method getCourse()

Perform the following operations to create a new method getCourse() 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 getCourse into the Name fi eld and click on the Browse button that is next to the Return Type combo box. On the opened Find Type wizard, type course into the top fi eld and select the Course (org.ws.entity) from the list and click on the OK button.

4. Click on the Add button to add one argument for this method. Enter cid into the Name column and keep the default data type java.lang.String unchanged. Your fi nished Add Business Method wizard should match the one that is shown in Figure 9.86 . 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.87 into this new method getCourse() . The newly added codes have been highlighted in bold.

The codes for this method is very simple since we utilized a built - in method fi nd() that is created and added into this session bean class automatically when this session bean is created. Let ’ s have a closer look at this piece of codes to see how it works.

Figure 9.85. The running result of our Web service operation QueryCourseID().

c09.indd 855

c09.indd 855 7/20/2011 11:12:53 AM7/20/2011 11:12:53 AM

www.traintelco.com

A. The built - in method fi nd() is called with the given course_id as the argument. The function of the fi nd() method is to try to fi nd a course record whose primary key is the given course_id . The query result is returned and assigned to a local Course object

result .

B. The query result is returned to the associated Web operation.

The point to be noted is that the returned object of this method is a Course instance, whose protocol is the entity class Course defi ned in our entity class Course.java .

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 compo- nents used in this fi le. To fi x 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 second Web service operation QueryCourse() to call this session bean method getCourse() to query the details for a given course_id .

Figure 9.86. The fi nished Add Business Method wizard.

Figure 9.87. The codes for the method getCourse().

A B

@Stateless

public class CourseFacade {

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

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

………

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

}

public Course getCourse(String cid) { Course result = find(cid);

return result;

} }

9.14.8.5 Create and Build Web Service Operation QueryCourse()

Perform the following operations to add a new operation QueryCourse() into our Web service project to perform this course details query:

1. Double click on our Web service project 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 QueryCourse into the Name fi eld and click on the Browse button that is next to the Return Type combo box. Type arraylist into the Type Name fi eld, and select the item

ArrayList (java.util) from the list, and click on the OK button.

5. Click on the Add button and enter courseID into the Name parameter fi eld. Keep the default type java.lang.String unchanged and click on the OK button to complete this new operation creation process.

Your fi nished Add Operation wizard should match the one that is shown in Figure 9.88 .

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.89 into this newly added operation.

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

A. An ArrayList instance al is created and this variable is an array list instance used to collect and store our query result, and return to the consuming project.

B. Before we can call the session bean method getCourse() to query the course details, we need fi rst to clean up the ArrayList instance al to make sure that it is empty.

C. The session bean method getCourse() is called to query the details for a given course_id . The courseID , which is an input parameter, works as the argument for that method. The query result is returned and assigned to the local variable result .

Figure 9.88. The fi nished Add Operation wizard.

c09.indd 857

c09.indd 857 7/20/2011 11:12:53 AM7/20/2011 11:12:53 AM

www.traintelco.com

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 fi x these errors, just right click on any space inside this code window, and select the Fix Imports item to fi nd and add those missed packages.

At this point, we have fi nished 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 Glassfi sh 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 fi ne, expand the Web Services node under our Web service project and right click on our Web service target fi le 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 fi eld, 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!

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

A B C D

E

@WebMethod(operationName = "QueryCourse")

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

//TODO write your implementation code here:

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

al.clear();

Course result = courseFacade.getCourse(courseID);

al.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());

return al;

}

Một phần của tài liệu practical database aprogramming with java (Trang 722 - 746)

Tải bản đầy đủ (PDF)

(791 trang)