Skip Headers
NetBeans Developing Applications with NetBeans IDE
Release 7.4

E40142-08
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

16 Developing with Java Persistence

This chapter describes the features the NetBeans IDE provides to support the JavaPersistence API.

This chapter contains the following sections:

16.1 About Developing with Java Persistence

The Java Persistence API handles how relational data is mapped to persistent entity objects, how these objects are stored in a relational database, and how an entity's state is persisted. The Java Persistence API is defined as part of the Java EE specifications, but can also be used in Java SE environments.

Java Persistence Features

The following features are part of the Java Persistence API:

For more on using Java Persistence in Java SE applications and for deploying application to non-Java containers, see Section 16.5.1, "How to Add Support for Java Persistence to the Project."

For more about the features of the Java Persistence API, see Chapter 16: Introduction to the Java Persistence API in the Java EE 6 Tutorial.

http://docs.oracle.com/javaee/6/tutorial/doc/

Support for XML Descriptors

Although you do not need to specify additional XML descriptors, you have the option of using them as an alternative to annotations or to supplement or override some annotations. Using an XML descriptor might be useful in externalizing object-relational mapping information. Also, multiple XML descriptors can be useful in tailoring object-relational mapping information to different databases.

For related information, see Section 13.1, "About Developing Enterprise Applications."

16.2 Creating a Persistence Unit

A persistence unit is required if you are using Java Persistence in your application. A persistence unit is a uniquely-named collection of properties that are used to determine how a specific set of entities in an application are managed and persisted.

Persistence units are defined in the persistence.xml file. You can have more than one persistence unit defined in persistence.xml, but each persistence unit must have a unique name.

Properties specified in a persistence unit include the following:

Persistence units can be packaged as part of a WAR or EJB-JAR file, or can be packaged as a JAR file that can then be included in your application.

16.2.1 Scope of the Persistence Unit

The scope of a persistence unit is determined by the location of persistence.xml. When you use a wizard to create a persistence unit, the IDE creates persistence.xml in the location appropriate for the scope. For example, if you use the IDE to create a persistence unit for an EJB module, the IDE generates persistence.xml in the src/conf directory of your EJB module. When the EJB JAR is built, it packages persistence.xml in the EJB JAR's META-INF directory. The scope of the persistence unit is the set of classes in the EJB JAR file.

If the scope is not explicitly specified in a persistence unit, by default all the entities in the EJB JAR file would be within the scope of the persistence unit defined in persistence.xml.

Note:

The location of persistence.xml determines the persistence root. The root of the persistence unit is the JAR file or directory that contains the META-INF directory containing persistence.xml.

16.2.2 Persistence Provider

A persistence provider refers to an implementation of the Java Persistence API. The persistence provider is a library that provides the functionality to persist objects in the application.

The IDE is bundled with the EclipseLink persistence provider. EclipseLink is the reference implementation and the default Java Persistence provider in the GlassFish application server. You can use EclipseLink as your provider, or specify a different persistence provider.

16.2.3 Data Source

A data source refers to the database where persistent entities are stored. The data source must be registered on the server and is specified using the JNDI name. If the transactions are container-managed JTA transactions, the data source must be a JTA data source. If the transactions are application-managed, the data source is specified according to the JDBC database connection registered with the IDE.

In Java SE environments, the database is specified either using a data source or by other means, depending on the requirements of the persistence provider used.

16.2.4 Transaction Types

A persistence unit specifies how transactions are managed in the application. The transaction type you can use depends on the target container. If you are deploying to a Java EE container, transactions can be container-managed or application-managed. If you are not deploying to a Java EE container, transactions must be managed by the application.

  • Container-managed transactions (JTA transactions). Container-managed transactions are handled by the container using the Java Transaction API (JTA). To use the Java Transaction API, you must deploy your application to a Java EE container and your data source needs to support JTA transactions.

    In persistence.xml, the transaction type for the persistence unit is set to JTA. If you are deploying to the GlassFish application server, this option is selected by default when you create the persistence unit.

  • Application-managed transactions (resource-local transactions). Application-managed transactions are handled by the application.

    In persistence.xml, the transaction type for the persistence unit is set to RESOURCE_LOCAL.

For related information, see Section 15.1, "About Developing with Enterprise Beans."

16.2.5 How to Create a Persistence Unit

A persistence unit is required if you are using Java Persistence in your project.

  1. In the Projects window, right-click the project node and choose New > Other.

  2. Select Persistence Unit in the Persistence category and click Next.

  3. Specify a unique Persistence Unit Name. In most cases you can keep the default name suggested by the IDE.

  4. Select a persistence provider Persistence Provider or library from the dropdown list, or add a new library by choosing New Persistence Library.

  5. Select a data source (see "Scope of the Persistence Unit") from the dropdown list. The data source can be a JDBC connection or a database connection. To appear in the list, the data source needs to be registered with the IDE.

  6. Select Use Java Transaction APIs if you want the container to manage the entities.

    Note:

    Java Transaction APIs are only available if you are deploying to a Java EE container. If you are not deploying to a Java EE container, the transaction needs to be managed by the application. For more, see Section 16.2.4, "Transaction Types."

  7. Specify a table generation strategy for your database.

  8. Click Finish.

When you click Finish, the file persistence.xml opens in the Source Editor.

In EJB and WAR projects, you can findpersistence.xml in the Projects window under the Configuration Files node. In the Files window, persistence.xml is located in the src/conf directory.

When packaged, persistence.xml is located in the META-INF directory of an EJB JAR archive or the WEB-INF/classes directory of a WAR archive.

16.3 Creating an Entity Class

In Java EE applications, you use entity classes to create persistent entity objects ("entities"). Entity classes are "plain old Java objects" (POJOs). Entity classes import the Java persistence library javax.persistence.Entity and are marked with the @Entity annotation in your source code.

About Entity Classes

Entities have the following characteristics:

Entity classes are not restricted to EJB modules in enterprise applications. Entity classes can be located in an EJB module or a web module and can be also used in Java SE applications.

When coding entity classes, you use annotations to map entities and entity relationships to a database. You do not need to use external XML descriptor files to map persistent objects to a database. The information about the data source is contained in a persistence unit (see Section 16.2, "Creating a Persistence Unit").

For additional information see Section 13.1, "About Developing Enterprise Applications."

16.3.1 How to Create an Entity Class

  1. Right-click the module project node in the Projects window and choose New > Other.

  2. In the New File wizard, select Entity Class from the Persistence category.

  3. Enter the name of the class.

  4. Select the location where you want to save the entity class.

  5. Select an existing package from the Package drop-down list or type the name of a new package.

  6. Set the type of the variable you want to use as the primary key. The default type for the primary key is Long.

  7. Click Finish.

When you click Finish, the IDE generates the entity class and opens the class in the Source Editor. Annotations in the entity class define the primary key and the primary key generation strategy for the entity.

16.3.2 How to Map Entity Classes

An entity class is used to represent a table in a database, and the fields in an entity class correspond to columns in that table. In an entity class, you can use annotations to specify how fields in an entity class are mapped to the corresponding database columns and tables.

For example, the following @Column annotation marking the field address maps the field to the column named CUSTOMER_ADDRESS in the database table.

    @Column(name = "CUSTOMER_ADDRESS")
    private String address;
        

When mapping a persistent field or property name to a column, you do not need to specify a @Column annotation for the field or property if the name of the mapped database column is the same as the field or property name because they are mapped by default.

Table 16-1 displays the annotations that are commonly used when mapping entity classes.

Table 16-1 Entity Class Mapping Annotations

Annotation Description

@Id

Specifies the primary key property or field of an entity.

@GeneratedValue

Allows you to specify the strategy that automatically generates the values of primary keys. Used with @Id.

@Column

Specifies a mapped column for a persistent property or field.

@ManyToMany

Defines a many-valued association with many-to-many multiplicity.

@ManyToOne

Defines a single-valued association to another entity class that has many-to-one multiplicity.

@OneToMany

Defines a many-valued association with one-to-many multiplicity.


For more on using annotations and annotation elements to map entities in an enterprise application, see the Java EE 6 Tutorial:

http://docs.oracle.com/javaee/6/tutorial/doc/

For more on the specifications on annotations and annotation elements, see the Java EE 6 API specifications for javax.persistence:

http://docs.oracle.com/javaee/6/api/javax/persistence/package-summary.html

For additional information see Section 14.1, "About Developing Application Clients."

16.3.3 How to Generate Entity Classes from a Database

In addition to writing entity classes from scratch, you can also generate a set of persistent entity classes for an existing database. You can use the New Entity Classes from Database wizard to generate the entity classes from a connected database or from a database schema.

To generate entity classes from a database:

  1. Right-click the module project node in the Projects window and choose New > Other.

  2. In the New File wizard, select Entity Classes from Database from the Persistence category.

  3. Select the source database that contains the tables that you want to use to generate the entity classes:

    • Data Source. Choose a data source from the dropdown list. Alternately, you can choose Add Data Source to create a new data source. The database must be running to choose this option.

      Note:

      When choosing a data source, the server must be running and the data source must be registered with the server.

      Note:

      If your target server is not a Java EE container, the dropdown list contains the database connections registered with the IDE.

    • Database Schema. Choose a database schema from the dropdown list. This option is available only if there is a database schema in your project's src/conf folder.

      After you select the source database, the tables in that database are listed in the Available Tables pane.

  4. Select any tables in the left pane and click the Add button. Any tables related to the tables you select are automatically added to the list in the right pane. The IDE will generate entity classes for each table listed in the right pane.

    Note:

    Deselect Include Related Tables if you do not want entity classes created for related tables

  5. Click Next.

  6. Confirm the name of the classes that will be generated for each table listed.

  7. Select the location where you want to save the entity classes.

  8. Select an existing package from the Package drop-down menu or type the name of a new package.

  9. Confirm that you want the IDE to generate named query annotations in the entity classes. If you do not want the IDE to generate the annotations, deselect Generate Named Query Annotations for Persistent Fields.

  10. Click Next.

  11. (Optional) Specify any mapping options.

  12. Click Finish.

When you click Finish, the IDE creates entity classes for each of the tables you specified in the wizard. The package containing the generated entity classes is selected in the Projects window.

Note:

When you select a data source or JDBC connection, the IDE also creates a database schema for the database and saves the schema in your src/conf folder.

Note:

To persist entity classes, your project requires a persistence unit.

For additional information see Section 13.1, "About Developing Enterprise Applications," and Chapter 23, "Working and Connecting with Databases."

16.3.4 How to Obtain an Entity Manager

An entity manager is associated with a group of managed entities called a "persistence context". Entities within a persistence context are associated with an entity manager instance. To use an entity manager, you first need to obtain an entity manager from the container.

To obtain an entity manager:

  1. Open the class where you want to add the entity manager resource.

  2. Right-click in the Source Editor and choose Persistence > Use Entity Manager from the popup menu.

The IDE generates the code to obtain an entity manager instance.

How the entity manager instance is obtained depends upon your project. For example, if you are using a container-managed entity manager, you can obtain an entity manager instance by injecting the entity manager resource directly using the @PersistenceContext annotation. If entities in your project are application-managed, you first need to obtain an EntityManagerFactory before you can obtain an entity manager. You can obtain an EntityManagerFactory by using the @PersistenceUnit annotation in a Java EE container, or by calling Persistence.createEntityManagerFactory in a Java SE environment.

For more on entity managers, see the Java EE 6 Tutorial:

http://docs.oracle.com/javaee/6/tutorial/doc/

16.4 Generating JPA Controller Classes

A JPA controller class is a wrapper for an entity class that provides clients with access to the database through the methods in the entity class. The JPA controller class contains the logic for creating, editing and destroying an entry in the data source, getting all of the entries in the data source, and getting a specific entry in the data source.

You can use the JPA Controller Classes from Entity Classes wizard to generate JPA controllers based on entity classes in your application and exception classes that are used by the controller classes. The wizard generates one JPA controller class for each entity class that you select and places the controller class in the specified location. Each generated JPA controller class contains create, edit and destroy methods and methods for retrieving the entities and uses an entity manager for managing entity persistence.

16.4.1 How to Generate a JPA Controller Class from an Entity Class

To generate a JPA controller class from an entity class:

  1. Choose File > New (Ctrl+N) from the main menu.

  2. From the Persistence category, select JPA Controller Classes from Entity Classes and click Next. The wizard displays all of the entity classes in the project.

  3. Add all of the entity classes for which you want to generate controller classes to the Selected Entity Classes list and click Next.

  4. Specify a package for the JPA controller classes.

  5. Click Finish.

After the wizard generates the JPA controller classes, the controller methods can be invoked from JSP pages or JSP converters or other classes in your application. If the database schema changes you can use the IDE wizards to again generate new entity classes and controller classes and then where necessary update the code that invokes the controller methods.

16.5 Adding Support for Java Persistence

Support for Java Persistence is available to Java EE and Java SE applications running on the Java EE platform. If you have a J2EE 1.4 application it is possible to use Java Persistence if the target container is running on the Java EE platform. The container does not need to be a Java EE container.

Note:

You cannot use a container-managed entity manager in a J2EE 1.4 application.

If your target server is not a Java EE container, you can add support for Java Persistence functionality by adding the EclipseLink library to the project or the classpath of the container. The EclipseLink library contains the necessary libraries to support Java Persistence. The EclipseLink library is bundled with the IDE.

16.5.1 How to Add Support for Java Persistence to the Project

Follow these steps to add support for Java Persistence.

  1. In the Projects window, expand your project node, right-click the Libraries node and choose Add Library.

  2. In the Add Library dialog box, select EclipseLink and click Add Library.

When you add the EclipseLink library to your project, the EclipseLink library will be packaged with the EAR or WAR file when you build the project.