Practical Database Programming With Java
.pdf
8.5 Build Java Web Project to Access SQL Server Database 687
Now close the project by clicking on the Close button located at the upper-right corner of this page. Our data updating action using the JSF pages and Java bean is successful.
Finally, let’s take care of the course data deleting action against our sample database using the JSF pages and Java bean techniques.
8.5.8 Delete Records from the Course Table Using JavaServer Faces and Java Beans
As we did for the course data updating action in the last section, we still want to use the Delete button defined in the CoursePage and the associated Delete() method defined in the managed bean CourseBean to perform this data deletion action.
First, let’s build the codes for the Delete() method in our managed bean CourseBean class.
8.5.8.1 Build Codes for the Delete() Method in the JSF Managed Bean
Open the code window of the managed bean CourseBean and browse to the Delete() method, and enter the codes shown in Figure 8.110 into this method.
Let’s have a closer look at this piece of codes to see how it works.
A.First, a returned boolean variable delete is created and initialized to false.
B.Then the DeleteCourse() method that is defined in the session bean CourseFacade and will be developed in the next section is called with the course_id as the argument to perform this course data deleting action.
C.If the returned value is false, which means that this action has failed, a warning message is displayed using our JDialog box to indicate this situation.
D.Otherwise, the course data deletion is successful. In fact, the returned value is not important to us and therefore a null is returned.
Now let’s build the codes for the DeleteCourse() method in our session bean class to perform this data-deleting action.
public Boolean Delete() {
Aboolean delete = false;
Bdelete = courseFacade.DeleteCourse(selectedItem);
Cif (!delete) {
|
msgDlg.setMessage("The course deleting is failed!"); |
|
msgDlg.setVisible(true); |
|
} |
D |
return null; |
|
} |
Figure 8.110. The codes for the Delete() method.
688 Chapter 8 Developing Java Web Applications to Access Databases
public boolean DeleteCourse(String cid) {
Aint delete = 0;
BString query = "DELETE FROM Course c WHERE c.courseId =:CourseID";
Cem.clear();
DQuery cQuery = em.createQuery(query);
EcQuery.setParameter("CourseID", cid);
Fdelete = cQuery.executeUpdate();
Gif (delete != 0)
return true; H else
return false;
}
Figure 8.111. The codes for the DeleteCourse() method.
8.5.8.2 Build Codes for the DeleteCourse() Method in the Session Bean
Open the code window for our session bean class CourseFacade and create a new method DeleteCourse(). Enter the codes shown in Figure 8.111 into this method.
Let’s have a closer look at this piece of codes to see how it works.
A.A local integer variable delete is created, and it is used to hold the running result of the execution of the data deleting action.
B.The course deleting statement string is created with a named parameter CourseID.
C.The EntityManager is cleaned up to make it ready for this data deleting action.
D.The createQuery() method with the deleting query string as the argument is executed to create this deleting query object cQuery.
E.The setParameter() method is executed to initialize the named parameter CourseID with the input argument cid, which is the selected course_id.
F.The deleting action is performed by calling the executeUpdate() method, and the running result of this deleting action is assigned to the local integer variable delete.
G.The running result of this deletion is exactly an integer number indicating how many rows have been successfully deleted from the Course table. If this returned result is not equal to 0, which means that at least one row has been deleted from the Course table and this deleting action is successful, a true is returned to indicate this situation.
H.Otherwise, the deleting action has failed, and a false is returned.
Now let’s build and run the project to test this data deleting action.
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 CSC-233B, from the CourseList box, and click on the Delete button to try to delete this course from our Course table.
To confirm this deleting action, two ways can be used. One way is to open the Course table from the Services window in the NetBeans IDE to check whether this course has
8.5 Build Java Web Project to Access SQL Server Database 689
Figure 8.112. The running result of deleting course action.
Table 8.8. The course CSC-233B record in the Course table
course_id |
course |
credit |
classroom |
schedule |
enrollment |
faculty_id |
|
CSC-233B |
Introduction to Algorithms |
3 |
TC-302 |
M-W-F: 11:00-11:55 AM |
19 |
K69880 |
|
|
|
|
|
|
|
|
been removed. Another way is to use the Select button to try to retrieve all courses taught by the selected faculty from our Course table to confirm this deleting action. Now let’s use the second way to do this checking since it is easy.
Make sure that the faculty member Jenney King is still in the Faculty Name field, and click on the Select button to try to retrieve all courses taught by this faculty. You can find that no course CSC-233B is displayed in the CourseList box, as shown in Figure 8.112, and this course has been deleted from the Course table successfully.
Now close the project by clicking on the Close button located at the upper-right corner of this page. Our data deleting action using the JSF pages and Java bean is successful.
It is highly recommended to recover this deleted course from the Course table to make our database clean and neat. Use the data shown in Table 8.8 to do this recovery job.
One easy way to recover this record is to open the Microsoft SQL Server 2008 Management Studio to insert a new row shown in Table 8.8 into our Course table. On the opened SQL Server 2008 Studio, expand to our dbo.Course table and right click on it, and select the Edit Top 200 Rows item to do this new row insertion.
The codes for the Back button in the CoursePage are not important in this application, and we’d like to leave this coding as a homework to the readers.
A complete Java Web application project JavaWebDBJSPSQL can be found from the folder DBProjects\Chapter 8 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1). You can download this project and test it in your computer if you like.
690 Chapter 8 Developing Java Web Applications to Access Databases
Next, let’s handle building another Web application project to access and manipulate the data against Oracle databases.
8.6 BUILD JAVA WEB PROJECT TO ACCESS AND MANIPULATE ORACLE DATABASE
In this section, we will discuss how to access the Oracle database and perform related data manipulations against our sample Oracle database using JavaServer Faces, Java bean, and another Java persistence technique—Hibernate. The structure block diagram of this kind of application is shown in Figure 8.113.
As we discussed in Section 5.3.6.2 in Chapter 5, Hibernate is an ORM library for the Java language, and it provides a framework for mapping an object-oriented domain model to a traditional relational database. Unlike the traditional Java Persistence API, Hibernate solves object-relational impedance mismatch problems by replacing direct persistencerelated database accesses with high-level object handling functions. Refer to Sections 5.3.6.2 and 5.3.6.6–5.3.6.7 in Chapter 5 to get more details about the configurations and implementations of Hibernate in Java database applications.
Based on Figure 8.113, we will build Java Web database applications to access and manipulate Oracle databases in the following structure:
1.Build and use JSF pages as the Web GUI or View to collect the users’ inputs and display the querying results.
2.Build and use Java session bean classes as the model to process data collected from the JSF pages, perform queries to the database and return the query results to the JSF pages.
3.Build and use another JPA, Hibernate, to map the database and manipulate data against the mapped database.
The operational principle of three blocks above is:
1.The GUI components built in the JSF pages are bound to the associated properties or methods defined in the Java session bean class, and these binding can be divided into two categories:
A.All value attributes for input and output tags are bound to the associated properties in the Java session bean class.
B.All action attributes for button tags are bound to the associated methods defined in the Java session bean class.
Web Container |
EJB Container |
JPA |
Oracle |
|
|
|
Database |
JavaServer |
|
|
Server |
Java Session |
Hibernate |
|
|
Faces (JSF) |
|
||
persistence |
|
||
Beans |
|
||
Pages |
|
||
|
API |
|
|
|
|
|
Figure 8.113. The structure of three-tier Web applications.
8.6 Build Java Web Project to Access and Manipulate Oracle Database 691
2.As the values of properties defined in the Java session bean are modified based on the queried result from the database, the bound values of the associated GUI components in the JSF pages are also modified immediately. Therefore, the input/output results can be collected and displayed between the JSF pages and Java beans through these binding relationships.
3.The navigations from one page to another page are based on the navigation rules defined in the faces-config.xml file.
Based on these structures and principles, now let’s begin to build our Java Web database applications to access Oracle databases to perform desired data actions. First, let’s create a new Java Web application project JavaWebDBJSPOracle.
8.6.1 Create a Java Web Application Project
Perform the following operations to create this new Java Web application project:
1.Launch NetBeans IDE and go to File > New Project menu item to open the New Project wizard. Select Java Web from the Categories list, and Web Application from the Projects list. Then click on the Next button to continue.
2. Enter JavaWebDBJSPOracle into the Project Name field and select the desired location to save this project by clicking on the Browse button. Your finished Name and Location wizard should match one that is shown in Figure 8.114. Click on the Next button to go to the next wizard.
3.Keep all default settings in the next wizard unchanged, which means that we need to use the Glassfish v3 as our application server and Java EE 6 as our platform in this project, and click on the Next button to continue.
4.In the Frameworks wizard, select the JavaServer Faces and Hibernate 3.2.5 from the list by checking them since we need to use both frameworks in this application. Also, click
on the dropdown arrow from the Database Connection combo box, and select our
Figure 8.114. The finished Name and Location wizard.
692 Chapter 8 Developing Java Web Applications to Access Databases
Figure 8.115. The finished Frameworks wizard.
sample Oracle database represented by its URL: jdbc:oracle:thin:@localhost:1521:XE [CSE_DEPT on CSE_DEPT], as shown in Figure 8.115. Click on the Finish button to complete this New Project creation process.
As soon as you create a new Web application project using the Hibernate framework, a Hibernate configuration file, hibernate.cfg.xml, will be automatically created by the NetBeans IDE at the root of the context classpath of the application, which is src/java in the Files window. The file is located in the <default package> under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multiview editor, or edit the XML directly in the XML editor.
To make our project work properly using the Hibernate tools, we need to do some modifications to this configuration file.
8.6.2 Modify the Hibernate Configuration File
Three modifications will be performed for this file; they are:
1.Add the hibernate.show_sql property to enables the debug logging of the SQL statements.
2.Add the hibernate.current_session_context_class property to enable Hibernate’s automatic session context management.
3.Add the hibernate.query.factory_class property to enable the Hibernate to perform the factory translator query automatically.
Let’s do those modifications one by one starting from the first one.
•Open the hibernate.cfg.xml in the Design tab.You can open the file by expanding Source Packages > <default package> in the Projects window and double clicking the configuration file hibernate.cfg.xml.
8.6 Build Java Web Project to Access and Manipulate Oracle Database 693
a |
b |
Figure 8.116. Modifications to the Hibernate configuration file.
Figure 8.117. The third modified property for the Hibernate configuration file.
•In the multiview XML editor, expand the Configuration Properties node under the
Optional Properties.
• Click on the Add button to open the Add Hibernate Property dialog box.
•In the dialog box, select the hibernate.show_sql property and set the value to true. The finished dialog box is shown in Figure 8.116a. This enables the debug logging of the SQL statements.
Perform the following operations to do the second modification:
•Expand the Miscellaneous Properties node and click on the Add button.
•In the opened dialog box, select the properties hibernate.current_session_context_class and set the value to thread to enable Hibernate’s automatic session context management. Your finished modification for this property is shown in Figure 8.116b.
For the third modification, follow the operational sequence described below:
•Click on the Add button again under the Miscellaneous Properties node and select hibernate.query.factory_class in the Property Name drop-down list.
•Type org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value, and then click on the OK button to complete this modification. Your finished modification for this property is shown in Figure 8.117.
Now click on the XML tab to open this modified configuration file in the XML format, and your modified file should match one that is shown in Figure 8.118.
In step A, the Oracle JDBC Driver is indicated by this driver class property, and the URL of our sample Oracle database is set by the url property. The username and
694 Chapter 8 Developing Java Web Applications to Access Databases
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
A<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
B<property name="hibernate.connection.username">CSE_DEPT</property> <property name="hibernate.connection.password">reback</property>
C<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property> </session-factory>
</hibernate-configuration>
Figure 8.118. The modified Hibernate configuration file.
password of our sample database are set to the username and password properties of the Hibernate connection class in step B. Starting from step C, our three modifications are set to those three related properties on the Hibernate component.
Make sure that all properties defined in your Hibernate configuration file are identical with those shown in Figure 8.118. In case that the sample database is locked, please open our sample Oracle database and login with the administrator username and password (SYSTEM and reback) to unlock it.
Next let’s create and configure the Hibernate components and related files since we need to use this component to perform database mapping and manipulations against our sample Oracle database in this application.
8.6.3 Create Hibernate Utility Files and Mapping Files
To correctly and smoothly implement the Hibernate component to map and access our sample database, we need to create some necessary utility files and mapping files for this component. First, let’s create the utility files for this component.
8.6.3.1 Create the HibernateUtil.java Helper File
To use Hibernate framework, we need to create a helper class that handles startup and that accesses Hibernate’s SessionFactory to obtain a Session object. The class will call Hibernate’s configure() method, loads the hibernate.cfg.xml configuration file, and then builds the SessionFactory to obtain the Session object.
In this section, we will use the New File wizard to create the Hibernate helper class file HibernateUtil.java. Perform the following operations to create this helper class file:
1.Right click on the Source Packages node in the Projects window and select New > Other menu item to open the New File wizard.
2.Select Hibernate from the Categories list and HibernateUtil.java from the File Types list, and then click on the Next button.
8.6 Build Java Web Project to Access and Manipulate Oracle Database 695
Figure 8.119. The finished New HibernateUtil.java dialog box.
3.Type HibernateUtil for the class name and cse.util as the package name, as shown in Figure 8.119. Click on the Finish button.
Next, let’s create Hibernate mapping files and related Java classes to perform the data actions against our sample Oracle database.
8.6.3.2 Generate Hibernate Mapping Files and Java Classes
In this section, we will use a group of plain old Java object (POJO) files to represent the data in the five tables in our sample Oracle database. The classes specify the fields for the columns in tables and use simple setters and getters to retrieve and write the data. To map POJO files to the five tables, we can use a group of Hibernate mapping files or use annotations in the class.
We can use the Reverse Engineering wizard and the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables that we selected. Alternatively, we can use wizards provided by the NetBeans IDE to help us to create individual POJOs and mapping files from scratch.
A point to be noted is that if you want to create mapping files for multiple tables, you may most likely want to use the wizards. In this application, we need to create five POJOs and five mapping files so it is fairly easy to do that with the help of wizards.
To use the POJOs and Mapping Files from Database wizard, we need to first create the reveng.xml reverse engineering file in the src/java directory where we created and stored our hibernate.cfg.xml.
8.6.3.2.1 Create the Hibernate Reverse Engineering File Perform the following operations to create this reverse engineering file:
1. |
Right click on the Source Packages node from the Projects window and select |
|
New > Other menu item to open the New File wizard. |
2. |
Select Hibernate from the Categories list and Hibernate Reverse Engineering Wizard |
|
from the File Types list. Click on the Next button to continue. |
696 Chapter 8 Developing Java Web Applications to Access Databases
Figure 8.120. The finished Database Tables wizard.
3.Type hibernate.reveng for the file name.
4.Specify src/java as the Folder location, and then click on the Next button.
5.Select all five tables from the Available Tables list and click on the Add All button to add these data tables to our Hibernate class, as shown in Figure 8.120.
6.Click on the Finish button to complete this process.
The wizard generates a hibernate.reveng.xml reverse engineering file located at the default package in our project.
Now let’s create Hibernate mapping files and POJOs from our sample Oracle database.
8.6.3.2.2 Create Hibernate Mapping Files and POJOs from Our Sample Database The Hibernate Mapping Files and POJOs from a Database wizard generates files based on tables in the connected database. When using the wizard, the NetBeans IDE generates POJOs and mapping files for us based on the database tables specified in reverse engineering file hibernate.reveng.xml, and then adds the mapping entries to hibernate.cfg.xml. By using this wizard, we can choose the files that we want the NetBeans IDE to generate, for example, only the POJOs, and select code generation options,generate code that uses EJB 3 annotations.
Perform the following operations to create mapping files and POJOs:
1. |
Right click on the Source Packages node in the Projects window and choose |
|
New > Other menu item to open the New File dialog. |
2. |
Select Hibernate from the Categories list and Hibernate Mapping Files and POJOs |
|
from a Database from the File Types list. Click on the Next button to continue. |
3.Select hibernate.cfg.xml from the Hibernate Configuration File drop-down list, if this configuration file has not been selected.
