Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migration of unmigrated content due to installation of a new plugin
Wiki Markup
{scrollbar}

Java Persistence API

The Java Persistence API is a new programming model under EJB3.0 specification (JSR220) for the management of persistence and object/relational mapping with Java EE and Java SE. With JPA, developers can easily develop java applications that perform operations on relational database management systems using Java objects and mapping. In that way, java applications developed using JPA are not only portable across different platforms, but also applications can be easily developed using simple yet powerful programming model provided by JPA. This greatly improves application maintainability against ever changing database world. JPA insulates applications from all the complexity and non-portable boilerplate code involved in database connectivity and operations. Apache geronimo uses OpenJPA for providing Java Persistence API to Java EE applications deployed in the server. Below sections illustrate developing applications using JPA and how to write various deployment descriptors and plans for Apache Geronimo.

The document is organized as follows.

Table of Contents

ShareAccount sample

This example illustrates developing an enterprise application that uses JPA for persistence. The database used is the embedded derby shipped with apache geronimo. Here, we present a persistence deployment descriptor (persistence.xml) that contains database connectivity and other information for the application. The persistence.xml is placed under META-INF/ directory of the application archive. The application contains an ejb module and a web module. EJB module uses a stateless session bean ShareHolderBean that uses JPA to perform database operations on the table SHAREACCOUNT in the ShareDB derby database. The SHAREACCOUNT table contains information about each shareholder along with the information regarding number shares he or she possesses currently in the account. The ShareHolderBean has methods that retrieve shareholder information, buy/sell shares of a particular shareholder, close the shareholder account etc. The web application has a servlet that looks up the ShareHolderBean and trigger the operations on it. The deployment descriptor information for the EJB module is provided using Java EE annotations in the respective bean classes. However, the persistence deployment descriptor information is provided using META-INF/persistence.xml file.

Code Block
JAVA
JAVA
borderStylesolid
titlesample.jpa.ShareAccount.java
package sample.jpa;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.PostLoad;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;
import javax.persistence.Table;

@Entity
@Table(name = "SHAREACCOUNT")
@NamedQuery(name="findThem", query="SELECT a FROM ShareAccount a")
public class ShareAccount implements Serializable {

   
    @Id
    private int shareAccountNo;
    private String ownerName;
    private int numberOfShares;
    @Version
    private int version;

    public ShareAccount(int shareAccountNo, 
                        String ownerName, 
                        int numberOfShares) {

      this.shareAccountNo = shareAccountNo;
      this.ownerName = ownerName;
      this.numberOfShares = numberOfShares;
        
    }

    public String toString() {
        return "Acc.# " + shareAccountNo +
               ", owner" + ownerName + 
               ", numberOfShares: " + 
                  numberOfShares + " $";
    }

    @PrePersist
    void prepersist() {
        System.out.println("pre persist!!");
    }
    
    @PreUpdate
    void preupdate() {
        System.out.println("pre update!!");
    }
    
    @PostUpdate
    void postupdate() {
        System.out.println("post update!!");
    }
    
    @PostLoad
    void postload() {
        System.out.println("post load!!");
    }

	public int getShareAccountNo() {
		return shareAccountNo;
	}

	public void setShareAccountNo(int shareAccountNo) {
		this.shareAccountNo = shareAccountNo;
	}

	public String getOwnerName() {
		return ownerName;
	}

	public void setOwnerName(String ownerName) {
		this.ownerName = ownerName;
	}

	public int getNumberOfShares() {
		return numberOfShares;
	}

	public void setNumberOfShares(int numberOfShares) {
		this.numberOfShares = numberOfShares;
	}

	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}
  
}

...

Note

The default namespace of the above XML document is http://java.sun.com/xml/ns/persistenceImage Removed. The XML elements that do not have a namespace prefix belong to the default namespace.

...

The Servlet client Test.java, looks up the ShareHolderBean and executes various methods on the ShareAccount entity. When the url http://localhost:8080/ShareHolderWEB/TestImage Removed is hit on a browser window, the following output is displayed.

No Format
borderStylesolid
titlehttp://localhost:8080/ShareHolderWEB/Test
_________________________________________
Looking up ShareHolderBean
Creating ShareAccount 1, Phani, 10
Account is successfully created
Looking up the ShareAccountNumber 1
Printing the details of ShareAccountNumber 1
Account Number = 1
Owner Name = phani
number of shares 10
version=1
_________________________________________

_________________________________________

buying shares 100
Printing the details of ShareAccountNumber 1
Account Number = 1
Owner Name = phani
number of shares 110
version=2
_________________________________________

_________________________________________
selling 50 shares of ShareAccountNumber 1
Printing the details of ShareAccountNumber 1
Account Number = 1
Owner Name = phani
number of shares 60
version=3
_________________________________________

_________________________________________
Printing all the available accounts
*******
Account Number = 1
Owner Name = phani
number of shares 60
version=3
*******
_________________________________________

_________________________________________
Setting the ShareAccount 1 with 500 shares and updating the database
Printing the details of ShareAccountNumber 1
Account Number = 1
Owner Name = phani
number of shares 500
version=0
_________________________________________

_________________________________________
Closing ShareAccountNumber 1
Printing the details of ShareAccountNumber 1
Account Number = 1
Owner Name = null
number of shares 0
version=0
_________________________________________

Inheritance relationship in entities

Entities can exhibit inheritance relationship among themselves. The entities involved in inheritance relationship can be persisted/updated/retrieved independently. There are several ways of realizing inheritance relationship among entities. There are as follows.

  • Single database table per class hierarchy
  • Separate database table per subclass
  • Single database table per concrete entity class

Single database table per class hierarchy

In this technique, a single database table is designated for entire entity class hierarchy exhibiting inheritance relationship. For example, if entity C extends entity B which extends entity A, the fields of all the entities are stored in a single table. The entities A, B and C can be persisted/updated/deleted/retrieved independently. This technique requires all the columns except for primary columns and columns of parent most entity A, should be nullable. This is because, suppose take the case when an entity B is being inserted. The entity B will have the values for the fields of A and itself but no values for fields of C. Since entire hierarchy uses a single table, the columns pertaining to entity C must be nullable. The same case arises when inserting entity A.

...

...