|NetBeans Developing Applications with NetBeans IDE
|PDF · Mobi · ePub|
This chapter contains the following sections:
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.
The following features are part of the Java Persistence API:
You can use an entity class to create a persistent entity object in Java EE applications. See Section 16.3, "Creating an Entity Class."
You can map persistent entity objects to a relational database using Java annotations or XML descriptors. See Section 16.3.2, "How to Map Entity Classes."
You can express queries in the native query language of the database or Java Persistence query language, which is an extension of the EJB query language.
You can package entity classes in JAR, WAR, EJB JAR, and EAR archives.
You can use an entity manager to perform Create Read Update Delete (CRUD) operations that involve entities. Section 16.3.4, "How to Obtain an Entity Manager."
You can specify the persistence provider you want to use in your application. Section 16.2.2, "Persistence Provider."
You can use Java Persistence API technology in Java SE applications. See Section 16.5.1, "How to Add Support for Java Persistence to the Project."
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.
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."
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:
The entity classes within the scope of the persistence unit
The persistence provider or library used for managing the set of entities scoped by that persistence unit
The data source used for the persistent storage of the managed entities
The transaction type the application uses
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.
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
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
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.
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.
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.
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.
persistence.xml, the transaction type for the persistence unit is set to
For related information, see Section 15.1, "About Developing with Enterprise Beans."
A persistence unit is required if you are using Java Persistence in your project.
In the Projects window, right-click the project node and choose New > Other.
Select Persistence Unit in the Persistence category and click Next.
Specify a unique Persistence Unit Name. In most cases you can keep the default name suggested by the IDE.
Select a persistence provider Persistence Provider or library from the dropdown list, or add a new library by choosing New Persistence Library.
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.
Select Use Java Transaction APIs if you want the container to manage the entities.
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."
Specify a table generation strategy for your database.
When you click Finish, the file
persistence.xml opens in the Source Editor.
In EJB and WAR projects, you can find
persistence.xml in the Projects window under the Configuration Files node. In the Files window,
persistence.xml is located in the
persistence.xml is located in the META-INF directory of an EJB JAR archive or the
WEB-INF/classes directory of a WAR archive.
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.
Entities have the following characteristics:
Each entity class usually represents a table in a relational database.
Each instance of an entity corresponds to a row in a table.
Persistent fields or properties correspond to columns in a table.
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."
Right-click the module project node in the Projects window and choose New > Other.
In the New File wizard, select Entity Class from the Persistence category.
Enter the name of the class.
Select the location where you want to save the entity class.
Select an existing package from the Package drop-down list or type the name of a new package.
Set the type of the variable you want to use as the primary key. The default type for the primary key is Long.
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.
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.
Specifies the primary key property or field of an entity.
Allows you to specify the strategy that automatically generates the values of primary keys. Used with @Id.
Specifies a mapped column for a persistent property or field.
Defines a many-valued association with many-to-many multiplicity.
Defines a single-valued association to another entity class that has many-to-one multiplicity.
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:
For more on the specifications on annotations and annotation elements, see the Java EE 6 API specifications for
For additional information see Section 14.1, "About Developing Application Clients."
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.
Right-click the module project node in the Projects window and choose New > Other.
In the New File wizard, select Entity Classes from Database from the Persistence category.
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.
When choosing a data source, the server must be running and the data source must be registered with the server.
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.
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.
Deselect Include Related Tables if you do not want entity classes created for related tables
Confirm the name of the classes that will be generated for each table listed.
Select the location where you want to save the entity classes.
Select an existing package from the Package drop-down menu or type the name of a new package.
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.
(Optional) Specify any mapping options.
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.
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
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."
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.
Open the class where you want to add the entity manager resource.
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:
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
destroy methods and methods for retrieving the entities and uses an entity manager for managing entity persistence.
Choose File > New (Ctrl+N) from the main menu.
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.
Add all of the entity classes for which you want to generate controller classes to the Selected Entity Classes list and click Next.
Specify a package for the JPA controller classes.
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.
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.
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.
Follow these steps to add support for Java Persistence.
In the Projects window, expand your project node, right-click the Libraries node and choose Add Library.
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.