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 6.1 Release.
Expected duration: 15 minutes
Tutorial Exercises
To follow this tutorial, you need the following software and resources.
| NetBeans IDE |
Web & Java EE, version 6.1 |
| Java Development Kit (JDK) |
version 6 or
version 5 |
| GlassFish application server |
V2 |
For this tutorial you need to register a local instance of GlassFish / Sun Java System Application Server with the IDE.
The GlassFish application server is bundled with the IDE. If you installed the application server as an option when you installed
the IDE, the server should already be registered with the IDE.
Prerequisites
This document assumes you have some basic knowledge of, or programming experience with, the following technologies:
- Java Programming
- NetBeans IDE
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 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 you can create our entity classes directly inside a web application.
For this tutorial you will use forms in JavaServer Faces (JSF) pages to read and modify the
data in the database.
- Choose File > New Project (Ctrl-Shift-N).
Select Web Application from the Web category and click Next.
- Type ZooApp for the project name and set the project location.
- Deselect the Use Dedicated Folder option, if selected.
(For this tutorial there is little reason to copy project libraries to a dedicated folder because
you will not need to share libraries with other users.)
Click Next.
- Set the server to GlassFish and set the Java EE Version to Java EE 5. Click Next.
- 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 you 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.
You create the persistence unit by defining its properties in persistence.xml which you will create in the web module.
After specifying the name of the persistence unit,
you will specify the persistence provider that the container uses for managing entity instances.
You also need to specify the data source and a table generation strategy.
You will create the persistence unit using the New Persistence Unit wizard.
You can also create a persistence unit in the New Entity Class wizard.
When creating an entity class, the wizard will prompt you to create a persistence unit if one does not exist.
Creating a Persistence Unit
- Right-click the ZooApp web application node in the Projects window and choose New > Other to open the New File wizard.
- From the Persistence category, select Persistence Unit and click Next.
- Keep the default Persistence Unit Name.
- 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.
- For the Data Source, use the default data source jdbc/sample.
The data source jdbc/sample is already configured to connect to the Java DB database that is bundled
with the GlassFish application server. You can use another database if you create a data source for the database.
- 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.
- Click Finish.
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 the 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 you will create two entity classes, Animal.java and Pavilion.java, that
represent the tables in the relational database you want to create.
You will then define some fields in the classes to represent the data.
The Java Persistence specification allows you to use annotations to
provide information to the container about the fields, such as object-relational mapping information.
Creating the Animal and Pavilion Entity Class
First you will create the entity classes Animal and Pavilion.
The classes represent the ANIMAL and PAVILION tables in the database.
When you create an entity class, the IDE adds the @Entity annotation to define the class as an entity class.
After you create the class, you will create fields in the class to represent the data that you want in your 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 entity classes, do the following:
- Right-click the ZooApp project node and choose New > Other.
- From the Persistence category, select Entity Class and click Next.
- Type Animal for the class name, entity for the
package, and leave the Primary Key Type as Long. Click Finish.
- Repeat the steps above to create the Pavilion class in the entity source package.
When you click Finish, the new entity classes open in the editor.
If you expand the entity node under the Source Packages in the Projects window, you can see that
the entity classes Animal and Pavilion are there.
Defining the Fields in the Animal Class
Open the Animal class in the editor and do the following:
- Add the following field declarations (in bold) to the class:
public class Animal implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String kind;
private String weight;
private Pavilion pavilion;
- Right-click in the Source Editor and choose Insert Code (Alt-Insert) and then select Getter and Setter to open the Generate Getters and Setters dialog box.
- In the Generate Getters and Setters dialog box, select all the fields and click Generate.
In the Generate Getters and Setters dialog box, you can use the Up arrow on the keyboard
to move the selected item to the Animal item and then hit the Space bar to select all fields in Animal.
- You now want to change the name of one of the columns that will be created in the Animal table
so that the column is called animalName instead of name.
You can use annotations to specify the name of the generated column by
adding the following annotation above the name field declaration:
@Column(name="animalName")
private String name;
- When you annotated the name field with the @Column annotation, the IDE displayed a warning
in the left margin next to the class identifier.
Click the warning icon in the margin and select Unify field access.
When you click Unify field access, the IDE moves the @Id and @GeneratedValue annotations from the
getId getter
so that the annotations are now directly above the private Long id.
- The pavilion column in our Animal table should also have a many-to-one relationship.
You can do this using annotations by adding the following annotation above the pavilion declaration:
@ManyToOne
private Pavilion pavilion;
- Press Alt-Shift-I to generate any necessary import statements for the class.
- Save your changes.
In the next step we will define the fields in the Pavilion entity class.
Defining the Fields in the Pavilion Class
Open the Pavilion class in the editor and do the following:
- Add the following field declarations (in bold) to the class:
public class Pavilion implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String address;
private Collection <Animal> animals;
- Add the following annotation above the name declaration to change the name of the generated column:
@Column(name="pavilionName")
private String name;
- Add the following annotation above the animals collection to specify a One-to-Many relationship for the entity:
@OneToMany(mappedBy="pavilion")
private Collection <Animal> animals;
- Right-click in the editor and choose Insert Code (Alt-Insert) and then select Getter and Setter.
- In the Generate Getters and Setters dialog box, select all the fields and click Generate.
- Click the warning icon in the margin and unify field access as you did for the Animal class.
- Press Alt-Shift-I to generate any missing import statements.
- 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
You now want to create some simple web pages to see if your database tables were created and if you can add data.
You 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.
- Choose File > New from the main menu.
Select JSF Pages from Entity Class from the Persistence category and click Next.
- In the New JSF Pages from Entity Class wizard, click Add All to select the two entity classes and click Next.
- Leave the JSF Pages Folder text field empty to save the JSF files in the default location.
- Specify entity as the package for the generated classes and click Finish.

When you click Finish, the IDE generates the required JavaServer Faces files so that you can run and test ZooApp.
Running the Project
In this exercise you will deploy the ZooApp web application project and test the application.
- Start the Java DB database by right-clicking the JavaDB node in the Services window and choosing Start Server.
- 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.
You can click on the links to view, add, edit or delete the data for animals and pavilions.
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:
- Right-click the web application node in the Projects window and select Properties.
- Select Frameworks in the Categories pane of the Project Properties dialog box and then click Add.
- In the Select Frameworks dialog box select Java Server Faces and click OK.
- 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.
When Modifying Pavilion Data You Get IllegalArgumentException
If you see the following exception:
java.lang.IllegalArgumentException: Expected a child component
type of UISelectItem/UISelectItems for component type javax.faces.SelectMany(animals). Found null.
the problem is probably caused by incorrect getter and setter methods for Collection <Animal>
in the Pavilion class.
Make sure that the getters and setters for Collection <Animal> looks like the following:
public Collection<Animal> getAnimals() {
return animals;
}
public void setAnimals(Collection<Animal> animals) {
this.animals = animals;
}
If the getters and setters are not correct in your project, do the following:
- Delete the Controller and Converter classes for the entity classes.
- Delete the animal and pavilion directories under the Web Pages node in the Projects window.
- Fix the getters and setters in the Pavilion entity class.
- Use the JSF Pages from Entity Class wizard to regenerate the JSF pages and Controllers and Converter classes.
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.