background image

Defining the Persistence Unit

<< Persistence in the Web Tier | Creating an Entity Class >>
<< Persistence in the Web Tier | Creating an Entity Class >>

Defining the Persistence Unit

As in JDBC technology, a DataSource object has a set of properties that identify and describe
the real world data source that it represents. These properties include information such as the
location of the database server, the name of the database, the network protocol to use to
communicate with the server, and so on.
An application that uses the Java Persistence API does not need to explicitly create a connection
to the data source, as it would when using JDBC technology exclusively. Still, the DataSource
object must be created in the Application Server.
To maintain the catalog of books, the Duke's Bookstore examples described in Chapters
"Further Information about Web Applications" on page 98
through
"Including the Classes,
Pages, and Other Resources" on page 466
use the Java DB evaluation database included with the
Application Server.
To populate the database, follow the instructions in
"Populating the Example Database" on
page 97
.
To create a data source, follow the instructions in
"Creating a Data Source in the Application
Server" on page 98
.
This section describes the following:
"Defining the Persistence Unit" on page 704
"Creating an Entity Class" on page 705
"Obtaining Access to an Entity Manager" on page 706
"Accessing Data from the Database" on page 708
"Updating Data in the Database" on page 708
Defining the Persistence Unit
As described in
"Accessing Databases from Web Applications" on page 703
, a persistence unit is
defined by a persistence.xml file, which is packaged with the application WAR file. This file
includes the following:
A persistence element that identifies the schema that the descriptor validates against and
includes a persistence-unit element.
A persistence-unit element that identifies the name of a persistence unit and the
transaction type.
An optional description element.
A jta-data-source element that specifies the global JNDI name of the JTA data source.
The jta-data-source element indicates that the transactions in which the entity manager
takes part are JTA transactions, meaning that transactions are managed by the container.
Alternatively, you can use resource-local transactions, which are transactions controlled by the
application itself. In general, web application developers will use JTA transactions so that they
don't need to manually manage the life cycle of the EntityManager instance.
Accessing Databases from Web Applications
The Java EE 5 Tutorial · September 2007
704