background image

Persistence in the Web Tier

<< JAR Files | Defining the Persistence Unit >>
<< JAR Files | Defining the Persistence Unit >>

Persistence in the Web Tier

Persistence in the Web Tier
This chapter describes how to use the Java Persistence API from web applications. The material
here focuses on the source code and settings of an example called bookstore, a web application
that manages entities related to a book store. This chapter assumes that you are familiar with the
concepts detailed in
Chapter 24, "Introduction to the Java Persistence API."
Accessing Databases from Web Applications
Data that is shared between web components and is persistent between invocations of a web
application is usually maintained in a database. Web applications use the Java Persistence API
(see
Chapter 24, "Introduction to the Java Persistence API"
) to access relational databases.
The Java Persistence API provides a facility for managing the object/relational mapping (ORM)
of Java objects to persistent data (stored in a database). A Java object that maps to a database
table is called an entity class. It is a regular Java object (also known as a POJO, or plain, old Java
object) with properties that map to columns in the database table. The Duke's Bookstore
application has one entity class, called Book that maps to WEB_BOOKSTORE_BOOKS.
To manage the interaction of entities with the Java Persistence facility, an application uses the
EntityManager
interface. This interface provides methods that perform common database
functions, such as querying and updating the database. The BookDBAO class of the Duke's
Bookstore application uses the entity manager to query the database for the book data and to
update the inventory of books that are sold.
The set of entities that can be managed by an entity manager are defined in a persistence unit. It
oversees all persistence operations in the application. The persistence unit is configured by a
descriptor file called persistence.xml. This file also defines the data source, what type of
transactions the application uses, along with other information. For the Duke's Bookstore
application, the persistence.xml file and the Book class are packaged into a separate JAR file
and added to the application's WAR file.
25
C H A P T E R
2 5
703