Java Persistence in the Java EE 5 Platform

This document takes you through the basics of developing a web application using Java™ Persistence. The Java Persistence API was introduced as part of the Java EE 5 platform. In this tutorial you will create a simple web application project. Though we will use persistence in our project, the Java Persistence API enables us to use persistence without needing to create an EJB module.

Using Java Persistence in your project greatly simplifies application development by removing the need for configuring deployment descriptors to provide object-relational mapping information for persistent fields or properties. Instead, you can use annotations to define these properties directly in a simple Java class.

Entity persistence is managed by the EntityManager API. The EntityManager API handles the persistence context, and each persistence context is a group of entity instances. When developing your application, you can use annotations in your class to specify the persistent context instance of your entity instances. The life-cycle of the entity instances is then handled by the container.

This document uses the NetBeans IDE 5.5 release.

Expected duration: 15 minutes

Prerequisites

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

Software Needed for the Tutorial

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

For this tutorial you need to register a local instance of Sun Java System Application Server with the IDE.

Tutorial Exercises


Setting Up the Web Application Project

The goal of this exercise is to create the ZooApp web application project. This application will take advantage of features of the new Java Persistence model. One of the features is that entity objects can be simple Java classes, so they no longer need to be placed in an EJB module and packaged in an EAR file. This means that we can create our entity classes directly inside a web application.

  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Web category and click Next.
  2. Name the project ZooApp, set the server to the Sun Java System Application Server, set the Java EE Version to Java EE 5, and click Next.
  3. Select the JavaServer Faces checkbox and click Finish.

Summary

In this exercise you created a Java EE 5 web application which will contain the entity classes.

Creating a Persistence Unit

In this exercise we will create a persistence unit to tell the container which entity classes are to be managed by the entity manager, and also the datasource used by those entities.

We create the persistence unit by defining its properties in persistence.xml which we will create in our web module. After specifying the name of our persistence unit, we will specify the persistence provider, which contains the APIs the container will use for managing entity instances. We also need to specify the data source and our table generation strategy. We will create the persistence unit using the New Persistence Unit wizard.

Note: We can also create a persistence unit in the New Entity Class wizard. When creating an entity class, the wizard will prompt us to create a persistence unit if one does not exist.

Creating a Persistence Unit

  1. Right-click the ZooApp web application node in the Projects window and choose New > File/Folder to open the New File wizard.
  2. From the Persistence category, select Persistence Unit and click Next.
  3. Keep the default Persistence Unit Name.
  4. For the Persistence Provider, use TopLink (default).

    The default provider is the TopLink Essential.jar. TopLink Essential.jar contains the libraries for Java Persistence. Our entity manager is located in TopLink Essential.jar.

  5. For the Data Source, use the default data source jdbc/sample.

    The default data source jdbc/sample is used to connect to the Java DB database that is bundled with the Sun Java System Application Server.

  6. Check that the persistence unit is using the Java Transaction API and that the Table Generation Strategy is set to Create so that the tables based on our entity classes are created when the application is deployed.
  7. Click Finish.

The New Persistence Unit wizard

When you click Finish, the IDE creates persistence.xml and opens it in the Source Editor in Design view. You can click XML in the toolbar of the Source Editor to see the XML for persistence.xml. This file contains all the information the Java EE 5 container needs to manage the entities and persistence of our application.

Summary

In this exercise, you created a persistence unit to specify the datasource, the entity classes to be persisted and the entity manager that the container will use to manage the life-cycle of the entities.

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 define some fields in the classes to represent the data. The Java Persistence specification allows us to use annotations to provide information to the container about the fields, such as object-relational mapping information.

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. Click Finish.

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 above the name field declaration:
        @Column(name="animalName")
  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 above the pavilion declaration:
        @ManyToOne
  6. Press Alt-Shift-F to generate any necessary import statements for the class.
  7. Save your changes.

In the next step we will create the Pavilion entity class.

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 to generate the getters and setters for the fields.
  3. Add the following annotation above the name declaration to change the name of the generated column:
        @Column(name="pavilionName")
  4. Add the following annotation above the animals collection to specify a One-to-Many relationship for the entity:
        @OneToMany(mappedBy="pavilion")
  5. Press Alt-Shift-F to generate any missing import statements.
  6. Save your changes.

Summary

In this exercise, you created two entity classes and defined fields. You also used annotations to define the properties of some of the columns in the tables that will be generated when you deploy the 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 and click Next.
  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. Start the Java DB database by choosing Tools > Java DB Database > Start Java DB Server.
  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 developed for the Java EE 5 platform. 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.

Next Steps

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

You can find more information about using Java Persistence in the Java EE 5 Tutorial.

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


Copyright and Trademark Notice