Java Persistence Example

Java Persistence API is the standard API used for the management of the persistent data and object/relational mapping.

Java Persistence Example

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 {   Long empid;
    @Id 
 
@GeneratedValue 
 
public Long getId() 
  
{ return id; }  
    public void setId(Long 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")
public class Book implements Serializable {

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. 

  1. Create Remote business interface: BookCatalogInterface
  2. Implement the Annotated Session Bean: BookCatalogBean
  3. Create the Entity bean: BookBank
  4.   Create the web client: WebClient
  5. Deploy book on the server.
  6. 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;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Collection;
import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="bookbank")
public class BookBank implements Serializable {

  long id;
  String title;
  String author;
  double price;

  //protected Collection <LineItems> lineitems;

  public BookBank() {
  super();
  }

  public BookBank(String title, String author, double price) {
  super();
  this.title = title;
  this.author = author;
  this.price = price;
  }

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)

 // Getter and setter methods for the defined properties..

  public long getId() {
  return id;
  }
  public void setId(long id) {
  this.id = id;
  }

  public String getTitle() {
  return title;
  }
  public void setTitle(String title) {
  this.title = title;
  }

  public String getAuthor() {
  return author;
  }

  public void setAuthor(String author) {
  this.author = author;
  }

  public double getPrice() {
  return price;
  }
  public void setPrice(double price) {
  this.price = price;
  }

}

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 ( 
 
ID int(11) NOT NULL auto_increment, 
 
TITLE varchar(50) NOT NULL, 
 
AUTHOR varchar(50) NOT NULL, 
 
PRICE decimal(12,2) NOT NULL, 
 
PRIMARY KEY  (ID)  
);    

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
Book catalog application, this is a simple Java interface declaring all business
methods.    

package entity.library;

import javax.ejb.Remote;
import java.util.Collection;
@Remote
public interface BookCatalogInterface {
  public void addBook(String title, String author, double price);
  public Collection <BookBank> getAllBooks();
}

IV. Annotated Session Bean Implementation Class:  
The EJB3 container creates instances of the session bean based on the implementation classes. The application itself never creates session bean instances. It
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.  

The code for the BookCatalogBean is given below.  

package entity.library;

import java.util.Iterator;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.Serializable;
import javax.ejb.Remote;
@Remote(BookCatalogInterface.class)
@Stateless
public class BookCatalogBean implements Serializable, BookCatalogInterface {
  @PersistenceContext(unitName="EntityBean")
 EntityManager em;
  protected BookBank book;
  protected Collection <BookBank> bookList;

 public void addBook(String title, String author, double price) {
  // Initialize the form
  if (book == null)
 book = new BookBank(title, author, price)
  em.persist(book);
  }

  public Collection <BookBank>getAllBooks() {
 bookList=em.createQuery("from BookBank b").getResultList();
 return bookList;
  }
}


The EntityManager API creates persistent entity instances and allows queries to be run on entities.  
 
   

Context context = new InitialContext();  
 
BookCatalogInterface bookcat = (BookCatalogInterface)  
   
context.lookup(BookCatalogBean.class.getName());  

 V. Web Client Code:

  Here is the full source code of the book client (WebClient.java):

<%page contentType="text/html; charset=UTF-8" %>
<%page import="entity.library.*, javax.naming.*, java.util.*"%>

 <%!
  private BookCatalogInterface bci = null;
  String s1,s2,s3;
  Collection list;
  
  public void jspInit() {
  try {
  
  InitialContext ic = new InitialContext();
  bci = (
  BookCatalogInterface
ic.lookup("book/BookCatalogBean/remote");

  System.out.println("Loaded Bank Bean");

  catch (Exception ex) {
  System.out.println("Error:"+
  ex.getMessage());
  }
  }
  public void jspDestroy() {
  bci = null;
  }
%>
  <%

  try {
  s1 = request.getParameter("t1");
  s2 = request.getParameter("aut");
  s3 = request.getParameter("price");

  if s1 != null && s2 != null && s3 != null) {
  Double price= new Double(s3);
  bci.addBook(s1, s2, price.doubleValue());
  System.out.println("Record added:");
 %>
  <p>
  <b>Record added</b> 
  <p>
  
  <%
  }
  list=bci.getAllBooks();
  for (Iterator iter = list.iterator(); iter.hasNext();){
  BookBank element = (BookBank)iter.next();
  %>
  <br>
 <p>Book ID: <b><%= element.getId() %></b></p>
  <p>Title: <b><%= element.getTitle() %></b></p>
  <p>Author: <b><%= element.getAuthor() %></b></p>
  <p>Price: <b><%= element.getPrice() %></b></p>

  <%
  }
  }// end of try
  catch (Exception e) {
  e.printStackTrace ();
  }
  %>

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">
<p align="center"><font size="6" color="#800000"><b>Welcome to <br>
Ejb3-Jboss 4.2.0 Tutorial</b></font>
Click <a href="ejb3/form.jsp">Book Catalog Example</a> to execute Library<br></p>
</body>
</html>


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>
  <loader-repository>
  book:archive=book.ear
  </loader-repository>
</jboss-app>


Application.xml
 

 <?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee" 
mlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="5" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/application_5.xsd">


  <display-name>JPA Example</display-name>
  <module>
  <web>
  <web-uri>book.war</web-uri>
  <context-root>/book</context-root>
  </web>
  </module>

  <module>
  <ejb>book.jar</ejb>
  </module>

</application>

  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>
  <persistence-unit name="EntityBean">
  <jta-data-source>java:/DefaultDS</jta-data-source>
  <properties>
  <property name="hibernate.hbm2ddl.auto"
  value="create-drop"/>
<property name="hibernate.dialect"  value="org.hibernate.dialect.HSQLDialect"/>  </properties>
  </persistence-unit>
</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">
<web-app >
</web-app>
1



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 2

  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 6

Price:  300.00