Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

8. Copy the following contents into Account.java.

Code Block
JAVA
JAVA
borderStylesolid
titlesample.jpa.Account.javaJAVA
package sample.jpa;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PostLoad;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;


@Entity
@Table(name = "ACCOUNTCME")
public class Account implements Serializable {

 @Id
 public int accountNumber;
 public String ownerName;
 public double balance;


 public Account() {
  accountNumber = (int) System.nanoTime();
 }

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

 @PrePersist
 public void prepersist() {
  System.out.println("pre persist!!");
 }

 @PreUpdate
 public void preupdate() {
  System.out.println("pre update!!");
 }

 @PostUpdate
 public void postupdate() {
  System.out.println("post update!!");
 }

 @PostLoad
 public void postload() {
  System.out.println("post load!!");
 }

 public int getAccountNumber() {
  return accountNumber;
 }

 public void setAccountNumber(int accountNumber) {
  this.accountNumber = accountNumber;
 }

 public String getOwnerName() {
  return ownerName;
 }

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

 public void setBalance(double balance) {
  this.balance = balance;
 }

 public double getBalance() {
 return balance;
 }
}

9. Similarly, create AccountInterface.java and copy the following contents.

Code Block
JAVA
JAVA
borderStylesolid
titlesample.jpa.AccountInterface.javaJAVA
package sample.jpa;

public interface AccountInterface {

 public Account open(int accountNumber) ;
 public double getBalance(int accountNumber);
 public void deposit(int accountNumber,double amount) ;
 public double withdraw(int accountNumber,double amount) ;
}

10. Similarly, create AccountBean.java.java and copy the following contents.

Code Block
JAVA
JAVA
borderStylesolid
titlesample.jpa.AccountBean.javaJAVA
package sample.jpa;


import javax.ejb.EJBException;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;


@Stateless
@Remote(AccountInterface.class)
public class AccountBean implements AccountInterface { 

 @PersistenceContext(type=PersistenceContextType.TRANSACTION)    
 private EntityManager manager;


 @TransactionAttribute(TransactionAttributeType.REQUIRED)    
 public Account open(int accountNumber) {
  Account account = manager.find(Account.class, accountNumber);
  if(account == null){
   account = new Account();
   account.ownerName = "anonymous";
   account.accountNumber = accountNumber;
   manager.persist(account);
   return account;
  }else{
   throw new EJBException("Account already exists..!!. Account Number = "+accountNumber);
  }
 }    

 @TransactionAttribute(TransactionAttributeType.REQUIRED)    
 public double getBalance(int accountNumber) {
  Account account = manager.find(Account.class, accountNumber);
  if(account==null)
   throw new EJBException("Account not found..!!. Account Number = "+accountNumber);
  return account.balance;
 }

 @TransactionAttribute(TransactionAttributeType.REQUIRED)
 public void deposit(int accountNumber, double amount) {
  Account account = manager.find(Account.class, accountNumber);
  if(account==null)
   throw new EJBException("Account not found..!!. Account Number = "+accountNumber);
  double new_balance = account.getBalance() + amount;
  account.setBalance(new_balance);
 }

 @TransactionAttribute(TransactionAttributeType.REQUIRED)    
 public double withdraw(int accountNumber, double  amount) { 
  Account account = manager.find(Account.class, accountNumber);
  if(account==null)
   throw new EJBException("Account not found..!!. Account Number = "+accountNumber);
  if (amount > account.getBalance()) {
   return 0;
  }else {
   double new_balance = account.getBalance() - amount;
   account.setBalance(new_balance);
   return amount;
  }
 }
}

11. As outlined above, right click on the META_INF directory of ContainerManagedJPA-EJB project and
create persistence.xml. Copy the following contents into persistence.xml.

Code Block
XML
XML
borderStylesolid
titlepersistence.xmlXML
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  
 http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

 <persistence-unit name="AccountUnit" transaction-type="JTA">
  <description>ContainerManagedJPA</description>
  <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
  <jta-data-source>AccountDS</jta-data-source>
  <class>sample.jpa.Account</class>
 </persistence-unit>
</persistence>

12. Since we are going to use EJB annotations, the META-INF/ejb-jar.xml will not have any declarations. The contents of the META-INF/openejb-jar.xml file should be as below. Otherwise, modify it accordingly.

Code Block
XML
XML
borderStylesolid
titleopenejb-jar.xmlXML
<?xml version="1.0" encoding="UTF-8"?>
<openejb-jar xmlns="http://openejb.apache.org/xml/ns/openejb-jar-2.2" 
 xmlns:naming="http://geronimo.apache.org/xml/ns/naming-1.2" 
 xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" 
 xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2">
 
 <sys:environment>
  <sys:moduleId>
   <sys:groupId>ContainerManagedJPA</sys:groupId>
   <sys:artifactId>EJB</sys:artifactId>
   <sys:version>1.0</sys:version>
   <sys:type>car</sys:type>
  </sys:moduleId>

  <dependencies>
   <dependency>
    <groupId>console.dbpool</groupId>
    <artifactId>AccountDS</artifactId>
   </dependency>
  </dependencies>

 </sys:environment>
 <enterprise-beans/>
 </openejb-jar>

...

5. Right click on the WebContent folder of the web project and navigate to New => HTML to create the index.html file as given in the screen shot. Click on the Next button and on the next screen click on the Finish button. The content of the index.html is provided below the screen shot.

Code Block
ActionScript
ActionScript
borderStylesolid
titleindex.htmlActionScript
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Input Account Numbers and Amount</title>
</head>
<body>
<form name="input" action="/ContainerManagedJPA-WEB/Test"method="get">
<table border="0">
<tr>
<td align="right"><font color="black" size="5"> Debit Account Number</font></td>
<td align="left"><input type="text" name="account1"></td>
</tr>
<tr>
<td align="right"><font color="black" size="5"> Credit Account Number</font></td>
<td align="left"><input type="text" name="account2"></td>
</tr>
<tr>
<td align="right"><font color="black" size="5"> Amount to be Transfered </font></td>
<td align="left"><input type="text" name="amount"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Submit"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>

...

9. Copy the below content into the servlet Test.java

Code Block
JAVA
JAVA
borderStylesolid
titleTest.javaJAVA
package sample.jpa;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

public class Test extends javax.servlet.http.HttpServlet 
 implements javax.servlet.Servlet {

 static final long serialVersionUID = 1L;

 @PersistenceContext(unitName="AccountUnit")
 private EntityManager em;

 @EJB AccountInterface accountBean;

 public Test() {
  super();
 }   	

 protected void doGet(HttpServletRequest request, 
                      HttpServletResponse response) 
                      throws ServletException, 
                      IOException {


 PrintWriter out = response.getWriter();

 int accNo1 = Integer.parseInt(
              request.getParameter("account1"));
 int  accNo2 = Integer.parseInt(
              request.getParameter("account2"));
 double amount = Double.parseDouble(
                 request.getParameter("amount"));

 try{
  Context ctx = new InitialContext();
  UserTransaction ut = (UserTransaction)
                        ctx.lookup("java:comp/UserTransaction");
  ut.begin();

  Account account = em.find(Account.class, accNo1);
  if(account.getBalance() < amount){
   throw new Exception("<font size=5>Account "+accNo1+
         " does not have enough balance "+amount+"</font>");
  }else{
   outputText(out, "2", "green", 
              "Message : Getting the balance amount available in Account Number "
              +accNo1+" in the Test Servlet");

   outputText(out, "5", "black","Account ="+
              accNo1+" : Current balance "+account.getBalance());
   out.println("<br/>");

   outputText(out, "2", "green","Message : Withdrawing amount ("+
              amount+") using AccountBean from the Account Number "+accNo1);

   accountBean.withdraw(accNo1, amount);

   outputText(out, "2", "green",
     "Message : Getting the balance amount available in Account Number "+accNo1+
     " in the Test Servlet after withdrawing");

   double balance = account.getBalance();
   outputText(out, "5", "black","Account ="+accNo1+
   " : After withdrawing the balance is "+balance);
   out.println("<br/>");

   outputText(out, "2", "green",
    "Message : Getting the balance amount available in Account Number "+
    accNo2+" in the Test Servlet");

   Account account2 = em.find(Account.class, accNo2);
   outputText(out, "5", "black","Account ="+
    accNo2+" : Current balance "+account2.getBalance());
   
   out.println("<br/>");

   outputText(out, "2", "green",
    "Message : depositing amount ("+amount+
    ") using AccountBean to the Account Number "+accNo2);

   accountBean.deposit(accNo2, amount);
   outputText(out, "2", "green",
   "Message : Getting the balance amount available in Account Number "+
   accNo2+" in the Test Servlet after depositing");

   outputText(out, "5", "black","Account ="+
              accNo2+" : After depositing the balance is "+
              account2.getBalance());

   out.println("<br/>");
   }
  ut.commit();
  }catch(Exception e){
  throw new ServletException(e);
 }
}  	

 protected void doPost(HttpServletRequest request, 
                       HttpServletResponse response) 
                       throws ServletException, IOException {
 }   	

 private void outputText(PrintWriter out, 
                         String fontsize, 
                         String color,
                         String text){
  out.println("<font size="+fontsize+" color="+
                color+">"+text+"</font>"+"<br/>");
 }
}

...

4. The above step will create AccountDB database. On the same screen, enter the below SQL command on the SQL Command/s textarea and select AccountDB in the Use DB combo box and click on the Run SQL button. This will create ACCOUNTCME table in the AccountDB database.

Code Block
SQL
SQL
borderStylesolidSQL
create table ACCOUNTCME (ACCOUNTNUMBER integer, OWNERNAME varchar(100), BALANCE decimal(15,2));

...

5. Also insert two rows using the below SQL command.

Code Block
SQL
SQL
borderStylesolidSQL
insert into ACCOUNTCME values (1, 'Phani',2000);
insert into ACCOUNTCME values (2, 'Nag',2000);

...