A Java Persistence Example
Java Persistence API
is the standard API used for the management of the persistent data and
object/relational mapping. Java Persistence API is added in Java EE 5 platform.
Persistence, deals with storing and retrieving of application data, can now be
programmed with Java Persistence API starting from EJB 3.0. Every application
server compatible with Java EE 5 supports the Java Persistent APIs.
Java Persistence API
is a lightweight framework based on POJO for object-relational mapping. Java
language metadata annotations and/or XML deployment descriptor is used for the
mapping between Java objects and a relational database.
Entity:
An entity can be considered as a lightweight
persistence domain object. An entity defines a table in a relational database
and each instance of an entity corresponds to a row in that table. An entity
refers to a logical collection of data that can be stored or retrieved as a
whole. For example, in a banking application, Customer and BankAccount
can be treated as entities. Customer name, customer address etc can be logically
grouped together for representing a Customer entity. Similarly account
number, total balance etc may be logically grouped under BankAccount
entity.
Entity beans:
Entity beans are enterprises beans, which represent
persistent data stored in a storage medium, such as relational database an
entity bean persists across multiple session and can be accessed by multiple
clients. An entity bean acts as an intermediary between a client and a database.
For example, consider a bank entity bean that is used for accessing account
details from a database. When a client wants to perform a transaction, the
information regarding their specific account is loaded into an entity bean
instance from the database. Operations are performed on the data present in the
instance and updated in the bank?s database at regular intervals.
The EJB 3.0
entity beans are used to model and access relational database tables. It is
a completely POJO-based persistence framework with annotations that specify how
the object should be stored in the database.
The EJB 3.0 container does the mapping from the objects to relational
database tables automatically and transparently. The Java developer no longer
needs to worry about the details of the database table schema, database
connection management, and specific database access APIs.
Entity beans do not
need to implement home interfaces and business interfaces. They
are optional.
Mapping with EJB3/JPA Annotations:
EJB3
entities are POJOs. Their mappings are defined through JDK 5.0 annotations (an
XML descriptor syntax for overriding is defined in the EJB3 specification).
Annotations can be split in two categories, the logical mapping annotations
which allows programmer to describe the object model, the class associations,
etc. and the physical mapping annotations which describes the
physical schema, tables, columns, indexes, etc. The combination of annotations from both categories makes an entity-based application.
Primary Key
Generation:
In EJB 3.0, a
primary key is used with @Id annotation. Depending upon the application
requirement, Id annotation can be used with different primary key generation
strategies defined by GeneratorType enum. The GeneratorTypes are TABLE,
SEQUENCE, IDENTITY, AUTO, and NONE.
Declaring an
entity bean:
Every bound persistent POJO class is an entity bean and
is declared using the @Entity
annotation (at the class level):
@Entity public class Book implements Serializable { @GeneratedValue public Long getId() { return id; } { this.id = id; } } |
@Entity
declares the class as an entity bean (i.e. a persistent POJO class), which tells
the EJB3 container that this class needs to be mapped to a relational database
table. @Id declares the identifier property of this entity bean. @GeneratedValue
annotation indicates that the server automatically generates the primary key
value.
The
class Book is mapped to the Book table, using the column id as its
primary key column.
Defining
the table:
@Table
is set at the class level; it allows you to define the table, catalog, and
schema names for your entity bean mapping. If no @Table is defined the default
values are used, that is the unqualified class name of the entity.
@Entity @Table(name="book") @SequenceGenerator(name = "book_sequence", sequenceName = "book_id_seq") |
The
@Table defines the table name. Each instance of the entity bean
represents a row of data in the table. Each column in the table corresponds to a
data attribute in the entity bean. The @SequenceGenerator
defines a sequence generator. A sequence is a database feature. It returns the
next Integer or Long value each time it is called.
Managing
Entities:
The
entity manager manages entities. The entity manager is represented by javax.persistence.EntityManager
instances. Each EntityManager instance is associated with a persistence context.
A persistence context defines the scope under which particular entity instances
are created, persisted, and removed. It is a set of managed entity instances
that exist in a particular data store. The EntityManager interface defines the
methods that are used to interact with the persistence context.
The
EntityManager Interface:
The
EntityManager API creates and removes persistent entity instances, finds
entities by the entity?s primary key, and allows queries to be run on
entities.
To
obtain an EntityManager instance, inject the entity manager into the application
component:
@PersistenceContext
EntityManager em;
Managing
an Entity Instance's Life Cycle:
You
manage entity instances by invoking operations on the entity by means of an
EntityManager instance. Entity instances are in one of four states: new, managed, detached, or removed.
New
entity instances have no persistent identity and are not yet associated with a
persistence context.
Managed
entity instances have a persistent identity and are associated with a
persistence context.
Detached
entity instances have a persistent identify and are not currently associated
with a persistence context.
Removed
entity instances have a persistent identity, are associated with a persistent
context, and are scheduled for removal from the data store.
A
Domain model of JPA represents the persistence objects or entities in the
database.
There are following steps that
you have to follow to develop a ?book? JEE application.
- Create Remote business interface: BookCatalogInterface
- Implement the Annotated Session Bean: BookCatalogBean
- Create the Entity bean: BookBank
- Create the web client: WebClient
- Deploy book on the server.
- Run web client on the web browser.
I.
The BookBank entity bean class:
In the Book catalog
example, we define a Book entity bean class. The bean has three
properties (title, author and price) to model a Book product. The id property is used to uniquely identify the Book bean instance by the EJB3
container. The id value is automatically generated when the bean is saved to the
database.
The code for the Book bean is given below.
package entity.library;
|
The
@Table annotation is used to specify the table name to be used by this
Entity bean.
The @Id annotation is used to
mark the id field as the primary key of the entity bean.
II. SQL Schema for the Book table mapped from the
Book bean:
CREATE
TABLE BOOKBANK ( |
III.
The Business Logic:
Now,
the next step is to develop the business logic of the application. The Book
catalog
application needs to be able to save a new Book object into the
database and
retrieve all existing Book objects from the database. We use EJB3 session bean
POJOs to implement the business logic.
To
implement a session bean, we first determine the interface it exposes. In the
methods.
package entity.library;
|
IV. Annotated Session Bean Implementation Class:
simply
asks the container for an instance of the session bean to use, either through
dependency injection or, for external components, through a JNDI lookup. The class is tagged with the @Stateless annotation, which tells the
container that the bean object does not maintain any client state information
between method invocations. The caller component gets a fresh and random BookCatalogBean
instance every time when it makes a bean method call.
In
order to use the entity beans in the session bean, you need a special utility
class called the EntityManager. The EntityManager acts as a generic DAO
(Data Access Object) for all entity beans in the JAR. It translates operations
on entity beans to SQL statements to the database. To obtain an EntityManager, the container creates one object and injects it into the session bean.
The
addBook() and getAllBooks() methods in the BookCatalogBean class show the
EntityManager in action. The EntityManager.persist() method takes a new
entity bean POJO and writes it to the database.
package entity.library;
|
The
EntityManager API creates persistent entity instances and allows queries
to be run on entities.
Context context = new
InitialContext(); |
V.
Web Client Code:
Here is the full source code of the book client (WebClient.java):
<%@ page contentType="text/html; charset=UTF-8" %>
|
The source code for the "index.jsp'
is given below that will actual call the client-design form.
<%@page language="java" %> <html> <head> <title>Ejb3 JPA Tutorial</title> </head> <body bgcolor="#FFFFCC"> |
The source code for the index.jsp is given below that will
call the web client.
<html> <head> <title>Library</title> </head> <body bgcolor="pink"> <h1>Library</h1> <hr> <form action="WebClient.jsp" method="POST"> <p>Enter the Title: <input type="text" name="t1" size="25"></p> <br> <p>Enter Author name: <input type="text" name="aut" size="25"></p> <br> <p>Enter Price: <input type="text" name="price" size="25"></p> <br> <p> <input type="submit" value="Submit"> <input type="reset" value="Reset"></p> </form> </body> </html> |
V. Deploy book application on the Application
Server
jboss-app.xml
The jboss-app.xml file defines a class loader for this application. It
makes it simpler for EJB 3.0 to find the default EntityManager.
<jboss-app> |
<?xml version="1.0" encoding="UTF-8"?>
|
Put both files in the EntityBean\code\deploymentdescriptors\ear
directory.
persistence.xml
The persistence.xml file contains one or several persistence-unit
element. Each persistence-unit defines the persistence context name, data
source settings, and vendor specific properties. In this example, we are
using the HSQL database that is default provided by the Jboss AS. The
hibernate property ?create-drop? will automatically create &
drop a table (according to the POJO class) each time when you deploy and run
the application on server.
<persistence> |
Put this files in the EntityBean\code\deploymentdescriptors\jar
directory.
0
web.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun
Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> |
Start command prompt, and
go to the EntityBean\code directory. Then type the command as:
C:\ EntityBean\code>ant build.xml
The Ant tool will deploy the book.ear file to the jboss-4.2.0.GA\server\default\deploy directory.
VI. Running the book
application
Open the web browser and type
the following URL to run the application:
http://localhost:8080/book
3
Click at the given link as Book Catalog Example:
4
Enter the Title, Author and Price for the book to the textbox then clicks the Submit button to get the result.
5
Book
ID: 1
Title: EJB-JPA
Author: Nisha
Price: 300.00