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

Practical Database Programming With Java

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

5.3 Exploring NetBeans IDE 6.8 269

When the form is open in Design view in the editor, the Palette window appears in the right side of the IDE. To add an element to the form, drag the element from the Palette window into the form area. After adding an element to the form, you need to modify the default value of the Variable Name property for that element.

In this application, we want to query and display details for some columns, such as the customer names and credit limit of the customers in the Customer table in the JavaDB sample database. Add the following components to this JFrame Form:

1.Drag a Label element from the Palette window and change the text to Customer Profile.

2.Drag a Label element from the Palette window and change the text to Customer Name.

3. Drag a Text Field element next to the Customer Name label and delete the default text.

4.When deleting the default text, the text field will collapse. You can resize the text field later to adjust the alignment of the form elements.

5.Drag a Label element from the Palette window and change the text to Credit Limit.

6. Drag a Text Field element next to the Credit Limit label and delete the default text.

7.Drag a Button element from the Palette window and change the text to Query.

8.Drag a Table element from the Palette window into the form.

9.Modify the Variable Name values of the following UI elements according to the values shown in Table 5.11.

Your finished JFrame Form window should match one that is shown in Figure 5.110. You may perform the following operations to improve the appearance of this

JFrame Form:

1. Modify the Variable Name value of an element by right clicking the element in the Design view and then choosing Change Variable Name. Alternatively, you can change the Variable Name directly in the Inspector window.

2.Resize the text fields and align the form elements.

3.Enable the Horizontal Resizable property for the text fields to ensure that the text fields resize with the window and that the spacing between elements remains constant.

4.Save all changes and modifications by selecting the File > Save All menu item.

Now that we have created a form we need to query and display the query result, now we need to create the code to assign events to the form elements.

In the next section, we will construct queries based on Hibernate Query Language to retrieve data from the Customer table in the default JavaDB sample database. After

Table 5.11. The modified elements in the JFrame form

GUI Component

Modified Variable Name

 

 

Customer name text field

NameTextField

Credit limit text field

CreditLimitTextField

Query button

QueryButton

Table

ResultTable

 

 

270 Chapter 5 Introduction to NetBeans IDE

Figure 5.110. The Design View of the JFrame Form.

we construct the queries, we will add methods to the form to invoke the appropriate query when the Query button is pressed as the project runs.

5.3.6.9 Creating the Query in the HQL Query Editor

In the NetBeans IDE, we can construct and test queries based on the HQL using the HQL Query Editor. As we type the query, the editor shows the equivalent or translated SQL query. When clicking on the Run HQL Query button in the toolbar, the NetBeans IDE executes the query and shows the results at the bottom of editor.

In this application, we will use the HQL Editor to construct simple HQL queries that retrieve a list of Customer’ details based on matching the first name or the last name. Before we can add the query to the class, we need to use the HQL Query Editor to test and confirm that the connection is working correctly, and that the query produces the desired results.

Perform the following operations to create and test this query in a HQL Editor:

1.Expand the <default package> node under the src/main/resources node that is under the Other Sources node in the Projects window.

2.Right click on the hibernate.cfg.xml file folder and choose Run HQL Query to open the HQL Editor.

3.

Test the connection by typing from Customer in the HQL Query Editor. Click the Run

 

HQL Query button ( ) in the toolbar.

4.

When clicking on the Run HQL Query button, you should see the query results in the

 

bottom pane of the HQL Query Editor, as shown in Figure 5.111.

If you click on the SQL button that is above the results shown in Figure 5.111, you should see the following equivalent SQL query:

select customer0_.CUSTOMER_ID as col_0_0_ from APP.CUSTOMER customer0_

5.3 Exploring NetBeans IDE 6.8 271

Figure 5.111. A sample running result of executing the HQL Query.

Figure 5.112. The mapped HQL query statement.

This is a mapped HQL query statement and is shown in Figure 5.112.

To further confirm and test the other query actions using the HQL Editor, perform the following two more query tests:

1.Type the following query in the HQL Query Editor and click Run HQL Query to check the query results when the credit limit is in the range of 50,000 and 150,000.

from Customer c where c.creditLimit between 50000 and 150000

The query returns a list of customers whose credit limits are between 50,000 and 150,000.

2.Open a new HQL Query Editor tab and type the following query in the editor pane. Click the Run HQL Query button to execute this HQL query.

from Customer c where c.name like ′N%′

The query returns a list of customers’ details for those customers whose names begin with the letter N.

272 Chapter 5 Introduction to NetBeans IDE

Notes: when typing a HQL query in the HQL Query Editor, for each column name you used in your query, you must use the mapped column name, or it is called the property in the HQL language, not the original column name in the relational data table. All mapped column names are located in the mapped entity file; in this application, its Customer.java is located under the customer.entity node. To check and use the appropriate mapped column name, you need to open that file and use mapped columns in that file.

Our testing query results show that the queries return the desired results.

Our next step is to implement the queries in the application so that the appropriate query is invoked by clicking the Query button in the form.

5.3.6.10 Adding the Query to the GUI Form

We now need to modify our main GUI file JavaMavenDBApp.java to add the query strings and create the methods to construct and invoke a query that incorporates the input variables. We also need to modify the Query button event handler to invoke the correct query and add a method to display the query results in the table.

Perform the following operations to add the query strings and create the associated query responding methods:

1.Open the GUI code file JavaMavenDBApp.java from the customer.ui node by double clicking on it and click the Source tab.

2.Add the codes shown in Figure 5.113 into to the class. The new added codes have been highlighted in bold.

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

A.Some necessary packages are first imported into this code file since we need to use related classes and components, and they are defined in those packages.

B.A system method setLocationRelativeTo() is called to locate our GUI Form in the center of the screen as the project runs.

C.Two static or named query strings are defined here with the HQL language. The first query string is used to query a detailed customer record based on the customer’s name, and the second is to query a detailed record based on the credit limit.

D.Inside the Query button’s event handler, an if-else selection structure is used to check if a query criterion is stored in the NameTextFieldor in the CreditLimitTextField. If any of them is not empty, the associated query function, either runQueryBasedOnName() or runQueryBasedOnCreditLimit(), is executed.

E.The detailed definition of the function runQueryBasedOnName() is shown here; it calls another function, executeHQLQuery(), with the static query string QUERY_ BASED_ON_NAME and the content of the NameTextField as the final query string argument.

F.The body of the function runQueryBasedOnCreditLimit() is shown here; it calls another function executeHQLQuery() with the static query string QUERY_BASED_

5.3 Exploring NetBeans IDE 6.8 273

package customer.ui;

Aimport org.hibernate.Query; import org.hibernate.Session;

 

import org.hibernate.HibernateException;

 

 

import javax.swing.table.*;

 

 

import java.util.*;

// for List & Vector classes

 

public class JavaMavenDBApp extends javax.swing.JFrame {

 

 

/** Creates new form JavaMavenDBApp */

 

 

public JavaMavenDBApp() {

 

B

initComponents();

 

this.setLocationRelativeTo(null);

// set the GUI Form at the center

 

}

 

Cprivate static String QUERY_BASED_ON_NAME = "from Customer c where c.name like '";

private static String QUERY_BASED_ON_CREDITLIMIT = "from Customer c where c.creditLimit >= "; private void QueryButtonActionPerformed(java.awt.event.ActionEvent evt) {

Dif(!NameTextField.getText().trim().equals("")) {

runQueryBasedOnName();

} else if(!CreditLimitTextField.getText().trim().equals("")) { runQueryBasedOnCreditLimit();

}

}

E private void runQueryBasedOnName() { executeHQLQuery(QUERY_BASED_ON_NAME + NameTextField.getText() + "%'");

}

F private void runQueryBasedOnCreditLimit() { executeHQLQuery(QUERY_BASED_ON_CREDITLIMIT + CreditLimitTextField.getText());

}

Gprivate void executeHQLQuery(String hql) { try {

HSession session = customer.util.HibernateUtil.getSessionFactory().openSession();

Isession.beginTransaction();

JQuery q = session.createQuery(hql);

KList resultList = q.list();

LdisplayResult(resultList);

Msession.getTransaction().commit();

N} catch (HibernateException he) {

he.printStackTrace();

}

}

Oprivate void displayResult(List resultList) { Vector<String> tableHeaders = new Vector<String>(); Vector tableData = new Vector(); tableHeaders.add("CustomerId"); tableHeaders.add("Name"); tableHeaders.add("CreditLimit"); tableHeaders.add("Email");

Pfor(Object o : resultList) {

customer.entity.Customer customer = (customer.entity.Customer)o; Vector<Object> oneRow = new Vector<Object>(); oneRow.add(customer.getCustomerId()); oneRow.add(customer.getName()); oneRow.add(customer.getCreditLimit()); oneRow.add(customer.getEmail());

tableData.add(oneRow);

}

Q ResultTable.setModel(new DefaultTableModel(tableData, tableHeaders));

}

Figure 5.113. The newly added codes for the GUI class JavaMavenDBApp.

274 Chapter 5 Introduction to NetBeans IDE

ON_CREDITLIMIT and the content of the CreditLimitTextField as the final query string argument.

G.The detailed definition of the function executeHQLQuery() is given here.

H.A try-catch block is used here to perform this query function. A java session bean is created by calling the method openSession() that is the running result of the method getSessionFactory(),whichisdefinedinthecustomer.util.HibernateUtil helper class.

I.The system method beginTransaction() is executed to begin performing this query.

J.The createQuery() method is called to create this HQL query string.

K.A List object, resultList, is created to hold the returned list query result.

L.A local function displayResult() is executed to display the list query result in our GUI Form, exactly in our added Table object.

M.The commit() method is executed to terminate this transaction.

N.The catch block is used to track and collect any possible exception that occurred during this transaction, and print them out if exceptions occurred.

O.The local function displayResult() is defined here. The main function of this method is to display four columns in the Customer table, CustomerId, Name, CreditLimit, and Email, with certain tabular format.

P.An extended for loop is used to pick up the contents for four columns in the Customer table. One point to be noted is that you have to use the full name, including the package and class names, to create this new customer instance. Here this full name is: customer.entity.Customer.

Q.Finally the setModel() method is executed to display this table with the selected format.

At this point, we have finished all coding development for this project. Now let’s build and run our project to see the running result.

Click on the Clean and Build Main Project button from the toolbar to compile and build our project. If everything is fine, perform the following operations to launch our application:

1.Right click on our main project node JavaMavenDBApp in the Projects window and choose the Properties item from the popup menu.

2.Select the Run category in the Project Properties dialog box.

3.Click on the Browse button and choose the class customer.ui.JavaMavenDBApp

from the Main classes list, as shown in Figure 5.114.

Figure 5.114. The selected main class for our project.

5.3 Exploring NetBeans IDE 6.8 275

Figure 5.115. A sample running result of our Maven project.

Figure 5.116. Another running result of our Maven project.

4.

Click on the Select

Main

Class button to close this dialog box, and click on the OK

 

button to finish this main class selection process.

5.

Click on the Run

Main

Project button in the main toolbar to launch the

 

application.

 

 

6.Type N to the Customer Name TextField and click on the Query button to try to retrieve all customers whose names start with N. The running result is shown in Figure 5.115.

7.Remove N from the Customer Name TextField and enter 50000 to the Credit Limit TextField. Click on the Query button to perform this query. The function of this query is to retrieve all customers whose credit limits are greater than or equal to 50,000. The running result of this query is shown in Figure 5.116.

276 Chapter 5 Introduction to NetBeans IDE

A complete Java Maven application project JavaMavenDBApp can be found from the folder DBProjects\Chapter 5 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1). You can download and run this application in your computer. However, before you can run this application in your computer, you need to have the following conditions met:

1.All related software have been installed in your computer, which include Apache Maven 2.2.1 or higher, NetBeans IDE 6.8 or higher, Java SDK 1.6 or higher.

2.The default JavaDB sample database has been connected and run in your computer. This can be done by right clicking on the sample database connection URL and selecting the Connect item from the popup menu in the Services window.

Next, let’s handle how to build PHP applications with NetBeans IDE 6.8.

5.3.7 Build a PHP Project

Personal Home Page (PHP) is a scripting language that is designed to develop dynamic web pages. The codes of PHP are embedded into the source document of HTML, and are able to be interpreted through a Web server into a processor module for PHP, and this creates the web page. When this is used as a programming language for general programming purposes, it is processed by an interpreter application that performs the operations of a selected operating system and creates output for the program through its regular channel for output. PHP is also able to work in a graphical form as a GUI. Today, PHP is there as a processor for the majority of Web servers, as well as an interpreter for the majority of operating systems and platforms of computing. This program was originally made by Rasmus Lerdorf in 1995. It has continued to develop since that time. It is now currently produced by what is called the PHP Group. This is free software, and it has been released through the PHP License.

5.3.7.1 Introduction to PHP

As we mentioned, PHP is a scripting language that is particularly useful for server-side development of the Web application, in which PHP will run on a Web server. The PHP code in a file that is requested is utilized by the PHP runtime. This is often used to create content for dynamic web pages.Additionally, it can be utilized for command-line scripting, as well as GUI applications for the client. Since PHP is able to be deployed on the majority of Web servers, the majority of operating platforms and systems are able to be used along with the database management systems. This program is fortunately free, and the PHP Group that develops it will provide the total source code for the users to build on- their-own applications, make it custom, and extend PHP for their own purpose.

The main purpose of the PHP is to mostly act like a filter as it takes input from a stream or from a file that has text or PHP instructions, and will then put out another group of data, and most often this data will be HTML. Today, PHP is primarily focused on providing server side scripting. This is close to other types of server side scripting languages, such as JavaFX and Java Scripts, to provide dynamic content through a Web server and to the client. This program has also lead to the development of a number of frameworks that will create a structure of design in order to provide for the rapid application development.

5.3 Exploring NetBeans IDE 6.8 277

PHP only parses code within its delimiters. Anything outside its delimiters is sent directly to the output and is not processed by PHP, although non-PHP text is still subject to control structures described within PHP code. The most common delimiters are <?php to open and ?> to close PHP sections. <script language=“php”> and </script> delimiters are also available, as are the shortened forms <? or <?=, which is used to echo back a string or variable, and ?>, as well as ASP-style short forms <% or <%= and %>. While short delimiters are used, they make script files less portable as their purpose, and this can be disabled in the PHP configuration, and so they are discouraged. The purpose of all these delimiters is to separate PHP code from non-PHP code, including HTML.

The first form of delimiters, <?php and ?>, in XHTML and other XML documents, creates correctly formed XML “processing instructions.” This means that the resulting mixture of PHP code and other markup in the server-side file is itself well-formed XML.

Variables are prefixed with a dollar sign, and a type does not need to be specified in advance. Unlike function and class names, variable names are case sensitive. Both doublequoted (“”) and heredoc strings allow the ability to embed a variable’s value into the string. PHP treats newlines as whitespace in the manner of a free-form language (except when inside string quotes), and statements are terminated by a semicolon.

PHP has three types of comment syntax: /* */ marks block and inline comments; // as well as # are used for one-line comments. The echo statement is one of several facilities PHP provides to output text, such as to a Web browser.

In terms of keywords and language syntax, PHP is similar to most high-level languages that follow the C style syntax. If conditions, for and while loops, and function returns are similar in syntax to languages such as C, C++, Java, and Perl.

5.3.7.2 Downloading and Installing Apache HTTP Web Server

Generally, you need the following software to build and run a PHP project in the NetBeans IDE:

NetBeans IDE 6.8 or higher

A PHP Engine (PHP 5 or higher)

• A Web Server (Apache HTTP Server 2.2 is recommended)

• A PHP Debugger (XDebug 2.0 or later)

You can install the PHP engine, Web server and database separately or use AMP (Apache, MySQL, PHP) packages. In this application, we want to install them separately since we want to use the default JavaDB sample database attached with the NetBeans IDE.

Let’s start to download an Apache HTTP Server by going to the site: http:// httpd.apache.org/download.cgi and select a download source mirror that is close to us. Click on that mirror to begin the downloading process. The current version is 2.2.15 for Windows applications. Therefore, click on the link: Win32 Binary without crypto (no mod_ssl) (MSI Installer): httpd-2.2.15-win32-x86-no_ssl.msi to begin this process. It is recommended to first save this file to your Temp folder in your root driver. Try to avoid downloading a zip server file since you need to compile the downloaded file if you did that.

278 Chapter 5 Introduction to NetBeans IDE

Figure 5.117. The Installation wizard.

After the downloading is complete, open the Temp folder and double click on the downloaded server file httpd-2.2.15-win32-x86-no_ssl.msi to install it. Click on the Run button to begin this installation. An Installation Wizard appears, as shown in Figure 5.117.

Click on the Next button to continue.

Click on the Accept the Terms radio button and the Next button to go to the next page.

In the next page, the installer displays the following information:

Network Domain

Server Name

Administrator’s Email Address

HTTP Server shortcut

You can modify these settings if you like others to access your site. However, we just want to use this server as our local server and do not want to expose it to others, therefore to make it simple, we just keep the default settings for this wizard, which are shown in Figure 5.118.

Click on the Next button to continue.

Select the Typical radio button for the set up type, and click on the Next button again to continue.

On the next wizard, make sure that the location you want to install this HTTP Server is: C:\Program Files\Apache Software Foundation\Apache 2.2, and click on the Next and Install button to begin this installation process.

Click on the Finish button to close this process when the installation is complete.

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