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

Practical Database Programming With Java

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

 

 

5.3 Exploring NetBeans IDE 6.8

249

 

 

 

 

 

 

 

 

 

 

 

 

 

<f:view>

 

 

 

 

 

<html>

 

 

 

 

 

<head>

 

 

 

 

 

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

 

 

 

 

<title>JSP Page</title>

Using the following codes to replace the outputText to navigate

 

 

to the ManufacturerDetails page

 

 

 

 

</head>

 

 

 

 

<h:commandLink action="#{manufacturer.showDetails(item)}"

 

<body>

 

 

value="#{item.manufacturerId}"/>

 

<h:form>

 

 

 

 

 

 

 

<h1><h:outputText value="Manufacturer Listing"/></h1>

 

 

 

 

<h:dataTable value="#{manufacturer.manufacturers}" var="item">

 

 

 

 

<h:column>

 

 

 

 

 

<f:facet name="header">

 

 

 

 

 

<h:outputText value="ManufacturerId"/>

 

 

 

 

</f:facet>

 

 

 

 

<h:outputText value="#{item.manufacturerId}"/>

</h:column>

<h:column>

<f:facet name="header"> <h:outputText value="Name"/>

</f:facet>

<h:outputText value="#{item.name}"/> </h:column>

…………

Figure 5.90. The modified codes in the ManufacturerList.jsp page.

…………

<h:outputLabel value="Email:" for="email" />

<h:inputText id="email" value="#{manufacturer.details.email}" title="Email" /> <h:outputLabel value="Rep:" for="rep" />

<h:inputText id="rep" value="#{manufacturer.details.rep}" title="Rep" /> </h:panelGrid>

<h:commandButton id="list" value="List" action="#{manufacturer.list}" />

</h:form>

<h1><h:outputText value="Hello World!"/></h1> </body>

</html>

</f:view>

Figure 5.91. The modified codes for the ManufacturerDetails page.

Now we can build and run the project to test the functions of this project.

5.3.5.15 Building and Running the Entire Java EE 6 Project

At this point, we have completed all coding jobs for this project. To see the running result, first let’s build the application by right clicking on our project JavaEEDBManufacturer and select the Clean and Build item, and deploy the application by right clicking on our project JavaEEDBManufacturer, and select the Deploy item.

If everything is fine, open a Web browser and go to the Manufacturer listing page at

URL, http://localhost:8082/JavaEEDBManufacturer-war/faces/ManufacturerList.jsp. You can find that all manufacturer IDs have been underscored. Click on the Manufacturer ID on the first row in the table to open the ManufacturerDetails page to query and display the detailed record for this manufacturer ID only.

250 Chapter 5 Introduction to NetBeans IDE

Figure 5.92. A running result of the project JavaEEDBManufacturer.

A running result of this project with a manufacturer ID of 19986982 is shown in Figure 5.92. You can click on the List button to return to the ManufacturerList page and reselect some other manufacturerID to see more results.

A complete Java EE 6 Database-related project JavaEEDBManufacturer 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 this project from that site and run it on your computer. However, you have to make sure that you have installed all required software before you can run this project on your computer:

1.Java Enterprise Edition 6

2.Glassfish v3

3.NetBeans IDE 6.8 or higher version of IDE.

For your convenience, another complete Java EE 6 application project JavaEEDBFaculty has been built and 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). The difference between this JavaEEDBFaculty project and the JavaEEDBManufacturer project is that a SQL Server database CSE_DEPT we built in Chapter 2 is used as the data source for the JavaEEDBFaculty project.

5.3 Exploring NetBeans IDE 6.8 251

To use a different data source in Java EE 6 applications, the only point to be noted is that you have to add the associated database driver to the Web application file; in that application, it is JavaEEDBFaculty-war. Refer to Appendix K to get a more detailed description about the development process for this kind of application.

Next let’s take care of building and implementing a Java Maven project.

5.3.6 Build a Maven Project

The Maven is exactly a project building and management tool and widely implemented in portable and cross-platform applications. In this section, we try to develop a Mavenbased application to illustrate how to use this kind of application to access a data source to perform data actions against different databases.

5.3.6.1 Introduction to Maven

Apache Maven is a tool used to build and manage software projects. Based on the concept of a project object model (POM), Maven can manage a project’s building, reporting, and documentation from a central piece of information with the plug-ins strategies. When you use Maven, you describe your project using a well-defined POM, Maven can then apply cross-cutting logic from a set of shared or custom-built plug-in.

Based on the definition of the Maven, it has two major functionalities: project building and project management.

Like other traditional project building tools, such as ASP.NET, ADO.NET, and Apache Ant, Maven has all of those functionalities to help developers to build and develop a professional application without problem. However, compared with those tools, Maven has the advantage in managing projects using a common interface. By using this common interface, the developers can save significant time to build and manage new projects with the help of the dependency management and reuse of common build logic through plug-ins.

Another benefit of using the Maven to build projects is that the Maven provides a so-called convention over configuration technique. By using this technique, all components and files you built in your project can be placed in certain default locations. For example, the source code is assumed to be in ${basedir}/src/main/java, and resources are assumed to be in ${basedir}/src/main/resources. Tests are assumed to be in ${basedir}/src/test, and a project is assumed to produce a JAR file. Maven’s adoption of convention over configuration goes farther than just simple directory locations; Maven’s core plug-ins apply a common set of conventions for compiling source code, packaging distributions, generating web sites, and many other processes.

Maven has plug-ins for everything from compiling Java code, to generating reports, to deploying to an application server. Maven has abstracted common build tasks into plug-ins which are maintained centrally and shared universally. Most of the intelligence of Maven is implemented in the plug-ins, and the plug-ins are retrieved from the Maven Repository. In fact, when you first time run the mvn install command with a brand-new

Maven installation, the Maven will retrieve most of the core Maven plug-ins from the Central Maven Repository.

Maven maintains a model of a project. When you build a Maven project, you are not just compiling source code into byte codes; instead, you are developing a description of

252 Chapter 5 Introduction to NetBeans IDE

a software project and assigning a unique set of coordinates to a project. With a model of a project, the following benefits can be obtained:

Dependency Management

Since a project is defined by a unique set of coordinates consisting of a group identifier, an artifact identifier, and a version, therefore projects can now use these coordinates to declare dependencies.

Remote Repositories

We can use the coordinates defined in the Maven POM to create repositories of Maven artifacts.

Universal Reuse of Build Logic

Plug-ins contain logic that works with the descriptive data and configuration parameters defined in POM; they are not designed to operate upon specific files in known locations.

Tool Portability/Integration

Tools like Eclipse and NetBeans now have a common place to find information about a project. Before the Maven, every IDE had a different way to store what was essentially a custom POM. Maven has standardized this description, while each IDE continues to maintain custom project files.

An artifact can be considered as an interface that contains all descriptions and properties of a project dependency built by the system or developers, and it can be stored in either local or remote repositories.

The first thing you will do when creating a Maven project is to select a group ID and an artifact ID. A group ID is used to describe the entire product, and artifact IDs are the basis of filenames for each item you distribute. The artifact ID may or may not overlap the group ID.

A typical Maven project structure or convention over configuration is shown in Figure 5.93.

/

+- src/

|

+- main/

|

|

+- java/

|

|

| +- ...

|

|

+- resources/

|

|

+- ...

|

+- test/

|

|

+- java/

|

|

| +- ...

|

|

+- resources/

|

|

+- ...

|

+- site/

|

 

+- xdoc/

|

 

+- ...

+- target/

|

+- ...

+- project.xml +- README.txt +- LICENSE.txt

Figure 5.93. A typical Maven project structure.

5.3 Exploring NetBeans IDE 6.8 253

There are just two subdirectories of this structure: src and target. The only other directories are metadata like CVS or .svn, and any subprojects in a multiproject build.

The src directory contains all source materials for building the project, its site, and so on. It also contains a subdirectory for each type: main for the main build artifact, test for the unit test code and resources, site, and so on.

The target directory is used to house all outputs of the build.

Within artifact-producing source directories, such as main and test, there is one directory for the language java under which the normal package hierarchy exists, and one for resources under which the structure that is copied to the target classpath provides the default resource definition.

At the top-level files descriptive of the project, there is a project.xml file and any properties, maven.xml or build.xml if using Ant. In addition, there are textual documents meant for the user to be able to read immediately on receiving the source: README. txt, LICENSE.txt, and BUILDING.txt, and so on.

Generally, a Maven project should have the key files or components in the following structure:

src/main/java: Contains handwritten Java code.

src/main/resources: All non-Java handwritten code, including Workflow and Xtext grammar.

target/generated/java: Contains generated code.

In the following sections, we want to use NetBeans IDE to create a Java Swing application from a Maven archetype. The application uses the Hibernate framework as the persistence layer to retrieve plain old Java objects (POJOs) from a sample relational database. We try to demonstrate how to use wizards provided in the IDE to help you create the necessary Hibernate files and add Hibernate dependencies to the POM. After creating the Java objects and configuring the application to use Hibernate, you can add a GUI interface for searching and displaying the data from the Customer table in the JavaDB default sample database.

Before we can start to build a Maven project to access a data source to perform certain data actions against databases, first we need to install and configure the building and developing environment for Maven applications.

5.3.6.2 Introduction to Hibernate Framework

Hibernate is an object-relational mapping (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 JPA, Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

One of the most primary features of using Hibernate is the mapping from Java classes to database tables and from Java data types to SQL data types. Hibernate also provides data query and retrieval facilities. Hibernate generates the SQL calls and relieves the developer from manual result set handling and object conversion, keeping the application portable to all supported SQL databases, with database portability delivered at very little performance overhead.

254 Chapter 5 Introduction to NetBeans IDE

Hibernate provides the ORM operational functions with the following properties:

1.Mapping

2.Persistence

3.Hibernate Query Language (HQL)

4.Integration

5.Entities and Components

6.Application Programming Interface (API)

5.3.6.2.1 Mapping Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotation. When using an XML file, Hibernate can generate skeletal source code for the persistence classes. This is unnecessary when annotation is used. Hibernate can use the XML file or the annotation to maintain the database schema.

Facilities to arrange one-to-many and many-to-many relationships between classes are provided. In addition to managing association between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type.

Hibernate supports the mapping of custom value types. This makes the following scenarios possible:

Overriding the default SQL type that Hibernate chooses when mapping a column to a property.

Mapping Java Enum to columns as if they were regular properties.

Mapping a single property to multiple columns.

5.3.6.2.2 Persistence Hibernate provides transparent persistence for Plain Old Java Objects (POJOs). The only strict requirement for a persistent class is a no-argument constructor, not necessarily public. Proper behavior in some applications also requires special attention to the equals() and hashCode() methods.

Collections of data objects are typically stored in Java collection objects, such as Set and List. Java generics, introduced in Java 5, are supported. Hibernate can be configured to lazy load associated collections. Lazy loading is the default as of Hibernate 3.

Related objects can be configured to cascade operations from one to the other. For example, a parent such as an Album object can be configured to cascade its save and/or delete operation to its child Track objects. This can reduce development time and ensure referential integrity. A dirty checking feature avoids unnecessary database write actions by performing SQL updates only on the modified fields of persistent objects.

5.3.6.2.3 Hibernate Query Language (HQL) Hibernate provides a SQL-inspired language called Hibernate Query Language (HQL) that allows SQL-like queries to be written against Hibernate’s data objects. Criteria Queries are provided as an objectoriented alternative to HQL.

5.3.6.2.4 Integration Hibernate can be used both in Java standalone applications and in Java EE applications using Servlets or EJB session beans. It can also be included as a

5.3 Exploring NetBeans IDE 6.8 255

feature in other programming languages. For example, Adobe integrated Hibernate into version 9 of ColdFusion that runs on J2EE app servers with an abstraction layer of new functions and syntax added into ColdFusion Markup Language (CFML).

5.3.6.2.5 Entities and Components In Hibernate jargon (jargon is terminology which is especially defined in relationship to a specific activity, profession, or group), an entity is a standalone object in Hibernate’s persistent mechanism that can be manipulated independently of other objects. In contrast, a component is subordinate to other entities and can be manipulated only with respect to other entities. For example, an Album object may represent an entity, but the Tracks object associated with the Album objects would represent a component of the Album entity if it is assumed that Tracks can only be saved or retrieved from the database through the Album object.

5.3.6.2.6 Application Programming Interface (API) The Hibernate API is provided in the Java package org.hibernate.

1.The org.hibernate.SessionFactory interface.

References immutable and thread-safe object creating new Hibernate sessions. Hibernatebased applications are usually designed to make use only of a single instance of the class implementing this interface and often exposed using a singleton design pattern.

2.The org.hibernate.Session interface

Represents a Hibernate session, such as the main point of the manipulation, performed on the database entities. The latter activities include (among the other things) managing the persistence state (transient, persisted, detached) of the objects, fetching the persisted ones from the database, and the management of the transaction demarcation.

A session is intended to last as long as the logical transaction on the database. Due to the latter feature, Session implementations are not expected to be thread-safe, nor to be used by multiple clients.

5.3.6.3 Installing and Configuring the Apache Maven

Since Maven is a Java tool, so before you can download and install Maven in your computer, you must have Java installed in order to proceed. More precisely, you need a JDK, since the JRE is not sufficient to support Maven.

The current version of Maven is 2.2.1, and it is distributed in several formats for your convenience. As you know, the Maven stored and distributed its artifacts in different repositories, either local or remote ones. Regularly, you can develop and build your own custom repositories inside your projects and with those sharing your project easily to get the right settings out of the box. However, you may need to use an alternative mirror for a particular repository without changing the project files. In that case, we encourage you to configure a Maven repository mirror closer to their location.

Some reasons to use a mirror are:

1.There is a synchronized mirror on the Internet that is geographically closer and faster.

2.You want to replace a particular repository with your own internal repository which you have greater control over.

3.You want to run maven proxy to provide a local cache to a mirror and need to use its URL instead.

256 Chapter 5 Introduction to NetBeans IDE

To configure a mirror of a given repository, you can provide it in your settings file ${user.home}/.m2/settings.xml, give the new repository its own id and URL, and specify the mirrorOf setting that is the ID of the repository you are using a mirror of.

We recommend downloading and installing Maven with its zip format since it is one of the most popular styles in traditional software installation.

To begin this downloading, go to the site http://maven.apache.org/ and click on the

Download item from the left column under the Get Maven category. Select the apache- maven-2.2.1-bin.zip file under the Mirrors column. Click and select the suggested mirror to start.

It is highly recommended to first save this file to your Temp folder, and then you can unzip and install this software to your computer.

Perform the following operations to install Maven to your computer:

1.Unzip the distribution archive, that is, apache-maven-2.2.1-bin.zip to the directory you wish to install Maven 2.2.1. This installation assumes that you chose the C:\ Program Files\Apache Software Foundation as this directory. The subdirectory apache-maven-2.2.1 will be created from the archive. Perform the following operations to complete this unzip process:

A. Open the Windows Explorer and create a new folder Apache Software Foundation under the C:\Program Files folder.

B.Go to the folder you just downloaded the Maven software; in this case, it is Temp folder. Right click on the downloaded apache-maven-2.2.1-bin.zip and select the Extract All . . . menu item from the popup menu.

C.Browse to the folder C:\Program Files\Apache Software Foundation and click on the Extract button.

2.Add the M2_HOME environment variable by performing the following operations:

A.Open the Control Panel and click on the Performance and Maintenance link, and double click on the System icon to open the System Properties window

B.Select the Advanced tab and the Environment Variables button. Click on the

New button under the User variables list. On the opened New User Variable dialog, enter M2_HOME to the Variable name field and C:\Program Files\

Apache Software Foundation\apache-maven-2.2.1 to the Variable value field. Be sure to omit any quotation marks around the path even if it contains spaces. Your finished New User Variable dialog box should match one that is shown in Figure 5.94.

C. Click on the OK button to complete this process.

3.In the same dialog, add the M2 environment variable in the user variables with the value %M2_HOME%\bin, as shown in Figure 5.95. Click on the OK buttons to complete this process.

Figure 5.94. The finished New User Variable dialog box.

5.3 Exploring NetBeans IDE 6.8 257

Figure 5.95. The added M2 environment variable.

Figure 5.96. The added Path environment variable.

Figure 5.97. The newly added JAVA_HOME path.

4.Optional: In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, such as the value -Xms256m or -Xmx512m.. This environment variable can be used to supply extra options to Maven.

5.In the same dialog, update or create the Path environment variable in the user variables and prepend the value %M2% to add Maven available in the command line, as shown in Figure 5.96.

6. In the same dialog, make sure that JAVA_HOME exists in your User variables or in

the System

variables, and it is set to the default location of your Java JDK, C:\

Program

Files\Java\jdk1.6.0_17, and that %JAVA_HOME%\bin is in your

Path environment variable. To do that check, select the Path variable from either the

User variables or System variables list, and click on the Edit button to open the whole path. If you cannot find those path variables, perform the following operations to add them:

A. From the System variables list, select the Path variable and click on the New button to open the New System Variable dialog box.

B.Enter JAVA_HOME into the Variable name field and C:\Program Files\ Java \jdk1.6.0_17 to the Variable value field, as shown in Figure 5.97.

C.Click on the OK button to close this dialog box.

258 Chapter 5 Introduction to NetBeans IDE

Figure 5.98. The added JAVA_HOME path variable.

Figure 5.99. A running result of the checking of the installed Maven tool.

D.To add the %JAVA_HOME%\bin to the Path environment variable under the System variables list, select the Path from the System variables list and click on the Edit button to open the Edit System Variable dialog. Move your cursor to the end of the path environment variable, and type a semicolon (;) and enter %JAVA_ HOME%\bin, as shown in Figure 5.98.

E.Click on the OK buttons to close this dialog and the System Properties window.

At this point, we have finished installing and configuring the Maven in your computer. Before we can continue, let’s first test this installation and configuration. Open a new command prompt and run mvn –version to verify that it is correctly installed. A sample of running result is shown in Figure 5.99.

5.3.6.4 Configuring Maven Inside the NetBeans IDE

If this is your first Maven project, you need to check the Maven configuration settings in the Options item under the Tools menu item in the NetBeans IDE 6.8. To complete this configuration, you should have Maven installed on your local system. Refer to the last section to complete this installation if you have not done that.

Another point to be noted is the Hibernate component, since we need to use this framework as the persistence to access the data in a data source. Perform the following operations to check and configure Maven and Hibernate framework:

1. Go to Tools > Options menu item to open the Options dialog box.

2.Click on the Maven tab from the opened dialog box.

3.Make sure that your Local Repository is the default location.

4.Click on the OK button to close this dialog box.

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