站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题Using Java Persistence in a J2EE 1.4 Web Application

Using Java Persistence in a J2EE 1.4 Web Application

摘要: This document takes you through the basics of how to add Java? Persistence functionality to a J2EE 1.4 web application. Though the Java Persistence API was introduced as part of the Java EE 5 platform, it is possible to use Java Persistence in a J2EE 1.4 application. The target container needs to be running on JDK 1.5, but it does not need to be a Java EE 5 container

Prerequisites

This document assumes you have some basic knowledge of, or programming experience with, the following technologies:

  • Java Programming
  • NetBeans IDE
  • MySQL Database Server

Software Needed for the Tutorial

For this tutorial you need to have the following software installed on your computer:

  • NetBeans IDE 5.5 (download).
  • Java Standard Development Kit (JDK) version 5.0 (download)
  • Access to a database server (For this tutorial we will use the MySQL 5.0 database server available at www.mysql.com/. If you want to use a MySQL database, make sure you have the MySQL JDBC driver. The driver is available here. If you want to use an Oracle database, you can find the current version of the Oracle JDBC driver (10.2.0.2) here.)

Tutorial Exercises


Setting Up the Environment

This tutorial shows you how to create the ZooApp application in an environment where there is no local installation of the Sun Java System Application Server or Java DB database server. Instead, we will use the bundled Tomcat web server as our container, and use a locally installed database server, in this case a MySQL database. The steps for setting up a database connection are also applicable to setting up a JDBC connection to other JDBC-compatible database servers, such as an Oracle database.

Before we can create our application, we need to confirm that the IDE and software are configured correctly and make sure that the database connection to our database is working correctly. We need to do the following:

Setting the Java Platform

We have to make sure that the Java platform for the IDE and the Tomcat web server are set to JDK 1.5.

  1. Choose Tools > Java Platform Manager from the main menu.
  2. In the Java Platform Manager dialog box, make sure that JDK 1.5 is set as the default platform and click Close.
  3. Choose Tools > Server Manager from the main menu.
  4. Select Bundled Tomcat in the Servers pane and click the Platform tab.
  5. Make sure that the selected Java Platform is JDK 1.5.
  6. Click OK.

Creating the Database Connection

In this example we use a locally installed MySQL database, but you can use any database that uses a JDBC driver. The IDE does not come with a database connection to the MySQL database, so we need to create a database connection in the Runtime window.

We need a MySQL JDBC driver to create a database connection to the MySQL database. If there is no MySQL JDBC driver, we need to add one.

Note: When you add a JDBC driver in the Add JDBC Driver dialog, you are providing the information necessary to allow the IDE to comunicate with the database. For example, this allows you to view the contents of a database in the Runtime window of the IDE. You may still need to add the appropriate driver to the web server library to allow the server to communicate with the database.

  1. In the Runtime window of the IDE, expand the Drivers node under the Database node.
    If there is no MySQL driver listed under the Drivers node, right-click the Drivers node and choose New Driver.
    In the New JDBC Driver dialog box, click Add, locate the JDBC driver for the database (mysql-connector-java-3.1.12-bin.jar), and then click OK to add the driver.
  2. Right-click the database driver and choose Connect Using to open the New Database Connection dialog box.
  3. In the New Database Connection dialog box, enter the URL, username and password for the database and click OK.

The Add JDBC Driver wizard

The New Database Connection dialog box

When you click OK, a new database connection node appears under the Databases node. If there is no open connection to the database, right-click the database connection node, choose Connect and supply the username and password, if necessary. We can test our connection by expanding the connection node to see the tables in the database, if any. Now that we have established a connection to our database, we can start creating our web application.

Summary

In this exercise we made sure our IDE and web server were running on the correct Java platform and that we had a working database connection to our database.

Setting Up the Project

In this exercise we create the ZooApp web application project. When creating the project, we first specify the project properties such as the J2EE version, the Java source level and the target server. We then need to configure the classpath of our project so that the appropriate JAR archives are available when we build and deploy the application.

Creating the Project

Because we are deploying to Tomcat instead of a Java EE container, we need to set the J2EE version to J2EE 1.4 when we create our project. But we need to set the source level of our project to 1.5 so that can use Java EE 5 functionality in our source code.

  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Web category and click Next.
  2. Name the project ZooApp.
  3. Set the server to the Bundled Tomcat server.
  4. Specify the project location.
  5. Set the Java EE Version to J2EE 1.4.
  6. Deselect Set the Source Level to 1.4.
    Note: By deselecting this, we are instructing the IDE to use the default source level. The default source level is determined by the default Java Platform of the IDE. In the previous exercise we set the default Java Platform to JDK 1.5.
  7. Click Next.
  8. Select the Java Server Faces framework checkbox and click Finish.

When you click Finish, the ZooApp web application appears in the Projects window of the IDE.

The New Web Application wizard

Adding Support for Java Persistence

In this tutorial we want to use Java Persistence in the Tomcat web container. Because the Tomcat web container is not a Java EE 5 container, we need to add support for Java Persistence by making sure the appropriate libraries are on the classpath. You add support for Java Persistence by adding the TopLink Essentials library to the classpath of your project. The TopLink Essentials library is bundled with the IDE and is located in <NETBEANS_HOME>\enterprise3\modules\ext\toplink, where <NETBEANS_HOME> is the installation directory of the IDE.

  1. In the Projects window, right-click the Libraries node under the ZooApp project node and choose Add Library.
  2. In the Add Library dialog box, select TopLink Essentials and click Add Library.
    Note: If the TopLink Essentials library is not listed, click Manage Libraries to open the Library Manager and create a library with toplink-essentials.jar and add the library to the project.

Adding Support for the Database Server

We now need to add the JAR archive for our database driver to the classpath.

  1. In the Projects window, right-click the Libraries node under the ZooApp project node and choose Add Jar/Folder.
  2. In the Add Jar/Folder dialog box, locate the driver for the database (mysql-connector-java-3.1.12-bin.jar) and click Open.

Summary

In this exercise we created a J2EE 1.4 web application. We then added the TopLink Essentials library and the database driver to the classpath of our web application. We can now start creating the entity classes and the web interface. The following steps are the same as in the Java Persistence in the Java EE 5 Platform tutorial.

Creating the Entity Classes

In this exercise we will create two entity classes, Animal.java and Pavilion.java, that represent the tables in the relational database we want to create. We will also use annotations to define some fields in the classes to represent the data.

We need a persistence unit in order to persist entity classes. The persistence unit specifies the datasource, the entity classes to be persisted and the entity manager for managing the life-cycle of the entities. The Tomcat server does not support container-managed persistence so we will use an application-managed entity manager. The entity manager must be specified as resource-local because Tomcat does not support JTA.

When we use the New Entity Class wizard, we are prompted to create a persistence unit if our application does not have one.

Creating the Animal Entity Class

First we will create the entity class Animal. This class represents the ANIMAL table in our database. When you create the entity class, the IDE adds the @Entity annotation to define the class as an entity class. After we create the class, we will create fields in the class to represent the data that we want in our table, and use annotations to provide additional information about some of the fields.

Each entity class must have a primary key. When you create the entity class, the IDE adds the @Id annotation to declare which field to use as the primary key. The IDE also adds the @Generated annotation to specify the key generation strategy for the primary Id.

To create the Animal class, do the following:

  1. Right-click the ZooApp project node and choose New > File/Folder.
  2. From the Persistence category, select Entity Class and click Next.
  3. Type Animal for the class name, entity for the package, and leave the Primary Key Type as Long.
  4. Click Create Persistence Unit to create the required persistence unit for our project.
  5. In the Create Persistence Unit dialog box, use the default name for the Persistence Unit and make sure the Persistence Library is TopLink Essentials.
  6. Select the MySQL database connection, make sure the table generation strategy is set to create on deploy and click Create.
  7. Click Finish to create the new entity class.

The Create Persistence Unit wizard

When you click Finish, the new entity class Animal.java opens in the Source Editor. In the Source Editor, do the following:

  1. Add the following field declarations to the class:
      String name;
      String kind;
      String weight;
      Pavilion pavilion;
  2. Right-click in the Source Editor and choose Refactor > Encapsulate fields to generate getters and setters for each of the fields. In the Encapsulate Fields dialog box, make sure that the getter and setter checkboxes are selected for all of the fields.
  3. Click Next in the Encapsulate Fields dialog box and then click Do Refactoring in the Refactoring tab of the Output window.
  4. We now want to change the name of one of the columns that will be created in the Animal table. We want our column to be called animalName instead of name. We can use annotations to specify the name of the generated column by adding the following annotation (in bold) above the name field declaration:
        @Column(name="animalName")
        private String name;
  5. We also want the pavilion column in our Animal table to have a many-to-one relationship. We can do this using annotations by adding the following annotation (in bold) above the pavilion declaration:
        @ManyToOne
        private Pavilion pavilion;
  6. Press Alt-Shift-F to generate any necessary import statements for the class.
  7. Save your changes.

The error highlighting in the IDE indicates that our class still has some errors, but this will be resolved after we create the Pavilion entity class in the next step.

Creating the Pavilion Entity Class

We now will create the entity class Pavilion representing the PAVILION table in our database. We will again use annotations in our class to specify the object-relational mapping of some of our fields. To create the Pavilion class, do the following:

  1. Right-click the ZooApp project node and choose New > File/Folder.
  2. From the Persistence category, select Entity Class and click Next.
  3. Type Pavilion for the class name, entity for the package, and leave the Primary Key Type as Long. Click Finish.

When you click Finish, the new entity class Pavilion.java opens in the Source Editor. In the Source Editor, do the following:

  1. Add the following field declarations to the class:
      String name;
      String address;
      Collection <Animal> animals;
  2. Choose Refactor > Encapsulate Fields and do the refactoring to generate the getters and setters for the fields.
  3. Add the following annotation (in bold) above the name declaration to change the name of the generated column:
        @Column(name="pavilionName")
        private String name;
  4. Add the following annotation (in bold) to specify a One-to-Many relationship for the animals collection mapped by pavilion in the Animal class:
        @OneToMany(mappedBy="pavilion")
        private Collection <Animal> animals;
  5. Press Alt-Shift-F to generate any missing import statements.
  6. Save your changes.

Summary

In this exercise, we created two entity classes and defined some of the fields in the classes. We also used annotations to define the properties of some of the columns in the tables that will be generated when the application is deployed. We also created a persistence unit with details required for managing the entities in our application.

Creating a Web Interface

We now want to create some simple web pages to see if our database tables were created and if we can add data. We will add Java Server Faces (JSF) pages to the application and use the JSF Pages from Entity Class wizard to quickly create a simple web interface.

  1. Choose File > New from the main menu. Select JSF Pages from Entity Class from the Persistence category and click Next.
  2. In the New JSF Pages from Entity Class wizard, click Add All to select our two entity classes.
  3. Leave the JSF Pages Folder text field empty to save the JSF files in the default location.
  4. Specify entity as the package for the generated classes and click Finish.

The JSF Pages from Entity Class wizard

When you click Finish, the IDE generates the required JavaServer Faces files so that we can run and test our ZooApp.

Running the Project

In this exercise we will deploy our ZooApp web application project and test our application.

  1. Make sure the database server is running.
  2. Right-click the ZooApp project node and choose Run Project.

When you click Run, a page opens in your browser with a menu enabling you to see a list of the pavilions and animals.

ZooApp Main Page

You can also add, edit or delete the data for animals and pavilions.

ZooApp Add Animal Page

Summary

In this exercise, you built the ZooApp web application. You then deployed and tested the ZooApp web application.

Troubleshooting

The following are some of the problems you may encounter when creating your project.

Problem with New JSF Pages from Entity Class Wizard

When using the wizard to create JSF pages from an entity class, you may see the following error message in the wizard:

This wizard can only be used in a web project with JSF support.

If you see this message you need to check that the Java Server Faces framework has been added to the project properties. You can add Java Server Faces support to your web project by doing the following:

  1. Right-click the web application node in the Projects window and select Properties.
  2. Select Frameworks in the Categories pane of the Project Properties dialog box and then click Add.
  3. In the Select Frameworks dialog box select Java Server Faces and click OK.
  4. Click OK in the Project Properties dialog box to close the window.

After adding the JSF Framework to the project properties, you should be able to create the JSF pages using the wizard.

Problem Establishing Connection Between Database and Server

If you can connect to the database from the IDE but you get a message that the server is unable to connect to the database, you may need to add the JDBC driver to the web server library. You should consult the documentation for your server for the correct location.

For example, to add the MySQL driver to the Sun Java System Application Server, you should add the mysql-connector-java-5.0.4-bin.jar to the APPSERVER_HOME/domains/domain1/lib/ext/ directory, where APPSERVER_HOME is the installation directory of the server.



Next Steps

For more information about using NetBeans IDE 5.5 to develop Java EE applications, see the following resources:

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE Java EE development features, join the mailing list.


↑返回目录
前一篇: Using Hibernate with the Java Persistence API
后一篇: Using Java Web Start in NetBeans IDE