Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 plans for apache geronimo.

...

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;
	}
  
}

...

@Entity : Marks the ShareAccount class as an entity that can be persisted entirely in the database.
@Table(name = "SHAREACCOUNT") : Designates the database table SHAREACCOUNT to the entity. The columns in the database table map to the attributes of ShareAccount entity.
@Id : This annotation designates primary key to the entity. In this case, it is the shareAccountNo attribute of the entity class.
@NamedQuery(name="findAccounts", query="SELECT a FROM ShareAccount a") : This annotation declares a named query by name findAccounts. This query retrieves all the share accounts from the database. Later in the ShareHolderBean, the NamedQuery is executed by using the name findAccounts.
@Version : The version attribute of the ShareAccount entity.

...

Code Block
JAVA
JAVA
borderStylesolid
titlesample.jpa.Test.java
package sample.jpa;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test extends 
  javax.servlet.http.HttpServlet 
  implements javax.servlet.Servlet {
  
  static final long serialVersionUID = 1L;
   
   public Test() {
	super();
   }   	
	
   protected void doGet(HttpServletRequest request,
                  HttpServletResponse response) 
                  throws ServletException, 
                  IOException {
				
    PrintWriter out = response.getWriter();
	        
    try {
     java.util.Properties env = 
       new java.util.Properties();

     env.put(Context.INITIAL_CONTEXT_FACTORY
       ,"org.apache.openejb.client.RemoteInitialContextFactory"); 
     env.put(Context.PROVIDER_URL, 
             "ejbd://127.0.0.1:4201");
	    		
     Context ctx = new InitialContext(env);
     out.println("Looking up ShareHolderBean");

     ShareHolder shareHolder = (ShareHolder)
            ctx.lookup("ShareHolderBeanRemote");
	            
     out.println("Creating ShareAccount 1, 
                   Phani, 10");
	            
     ShareAccount sa = 
         shareHolder.openShareAccount(1,"phani", 10);
     if(sa == null){
	out.println("account could not be created.");
	out.println("May be, account already 
                            exists. Check the database.");
           	
     }
     else {
        out.println("Account is successfully created");
     }
     out.println("Looking up the ShareAccountNumber 1");
     sa = shareHolder.findShareAccount(1);
     out.println("Printing the details of ShareAccountNumber 1");
     printShareAccount(sa,out);
     out.println("");

     out.println("buying shares 100");
     sa = shareHolder.buyShares(1, 100);
	            
     out.println("Printing the details of ShareAccountNumber 1");
     printShareAccount(sa,out);
     out.println("");

     out.println("selling 50 shares of ShareAccountNumber 1");
     int numberShares = shareHolder.sellShares(1, 50);
     if(numberShares == 50){
       out.println("Printing the details of ShareAccountNumber 1");
       sa = shareHolder.findShareAccount(1);
       printShareAccount(sa,out);
     }
     else if(numberShares == -1){
       out.println("ShareAccountNo can not be found");
     }else {
       out.println("The number shares available are less than 50");
     }
     out.println("");

     List<ShareAccount> saList = shareHolder.listAccounts();
     out.println("Printing all the available accounts");
     for (int i = 0; i < saList.size(); i++){
		out.println("*******");
		printShareAccount(saList.get(i),out);
		out.println("*******");
		out.println("");
	}
     out.println("");

     out.println("Setting the ShareAccount 1 with 500 shares 
                  and updating the database");
     sa = new ShareAccount(1,"phani",0);
     sa.setNumberOfShares(500);
     shareHolder.updateShareAccount(sa);
     out.println("Printing the details of ShareAccountNumber 1");
     printShareAccount(sa,out);
     out.println("");

     out.println("Closing ShareAccountNumber 1");
     sa = shareHolder.close(1);
     if(sa == null){
        out.println("Account is not found="+1);
     }else{
        out.println("Printing the details of ShareAccountNumber 1");
	printShareAccount(sa,out);
     }

   }
   catch(Exception e){
     e.printStackTrace();
     throw new ServletException(e);
   }
}  	

 protected void doPost(HttpServletRequest request, 
                      HttpServletResponse response) 
                  throws ServletException, IOException {
		
 }  
 private void printShareAccount(ShareAccount sa, PrintWriter out){
    if(sa != null){
    out.println("Account Number = "+sa.getShareAccountNo());
    out.println("Owner Name = "+sa.getOwnerName());
    out.println("number of shares "+sa.getNumberOfShares());
    out.println("version="+sa.getVersion());
    }else{
     out.println("ShareAccountNo can not be found");
    }
 }
}

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