ustomer Management - Entity Bean
  
 James Smith's Java is all about making it WORK , not just to understand the concept , its abt Solutions not Problems
What Is an Entity Bean? :: Like Details ? Click here

An entity bean represents a business object in a persistent storage mechanism. Some examples of business objects are customers, orders, and products. In the J2EE SDK, the persistent storage mechanism is a relational database. Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table.

You might be thinking why we are into Entity Bean first , where as all the computer books start with session bean , Thats cause they are Authors , not programmers most of them , Practicals is much heavier than writing 1000 pages of some stupid text .

Entity Beans are related to storing information into database and reading them. if u like to go indepth go to sun site , they know how to talk for years even if they get lost inbetween .... and leave u blinking...

CMP : Container Managed Persistance

In CMP the interation with database is Automatic u dont need to write db connection code or Connection close code , Infact if u r using CMP , u need not even write Select , Insert, Update, Delete Statements , the container writes it for u its a lazy way of programming but still very fast , Is so funny that tables are created on deployment and can be dropped on undeployment of an Application .. somehow i wish to avoid this .. as it will be difficult to understand Entity Bean if u go by this

BMP : Bean Managed Persistance

BMP is more or less reverse of CMP here u need to write db connection code and close codes , all the Select , Insert, Update, Delete Statements must be written . but this gives u more flexibility as a programmer which i love we will concentrate on BMP whenever we talk abt Entity bean from now on..
To write an Entity Bean or infact even a session bean u must write 4 different set of codes or min 4 java scripts

1. Remote Interface : Java file

2. Home Interface : Java file

3. Bean Implementation : Java file

4. Client code : Java / JSP / Servlet / WML or whatever u can dream of


 
  Remote Interface
The remote interface is the business end of the EJB. This is the set of actual services provides by the EJB. (or)

A remote interface defines the business methods that a client may call. The business methods are implemented in the enterprise bean code. ,

please note that marked in red are like a code skeleton

Black and bold is for Observation

/*
----------------------------------------------------------------------------------------------
Code by James Smith : james_smith73@yahoo.com
File Name : ManageCustRemote.java
The codes written in Home Interface are the one which a client can access
for his busn needs 
----------------------------------------------------------------------------------------------
*/

package EJB.ManageCust;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface ManageCustRemote extends EJBObject 
{
	public void setCustId(String CustId) throws RemoteException;
	public String getCustId() throws RemoteException;
	
	public void setCustName(String CustName) throws RemoteException;
	public String getCustName() throws RemoteException;
	
	public void setCustPh(String CustPh) throws RemoteException;
	public String getCustPh() throws RemoteException;
	
	public void setCustPlan(String CustPlan) throws RemoteException;
	public String getCustPlan() throws RemoteException; 
	
}

The above program allow the client to access methods like setCustId, getCustId etc which in turn allow him to read / write /update database ..
  Home Interface
The home interface is the book-keeping interface. It helps clients create a new instance of an EJB, or to find an existing instance of an EJB.

The methods used to find existing EJBs are known as "finder" methods. Since session beans are not designed to be shareable, there are no session bean finder methods.

The Home interface contains a single create() method, which returns an object of the remote interface type

/*
----------------------------------------------------------------------------------------------
Code by James Smith : james_smith73@yahoo.com
File Name : ManageCustHome.java
The codes written in Home Interface are the one which help in creating
or finding an EJB
----------------------------------------------------------------------------------------------
*/

package EJB.ManageCust;

import java.util.Collection;
import java.rmi.RemoteException;
import javax.ejb.*;

public interface ManageCustHome extends EJBHome 
{
  public ManageCustRemote create(String CustId, String CustName,String CustPh, String CustPlan) 
  	throws RemoteException, CreateException;
  public ManageCustRemote findByPrimaryKey(String primaryKey) throws FinderException, RemoteException;
  public Collection findInRange(int lowerLimit, int upperLimit) throws FinderException, RemoteException;
}
  Bean Implementation

The home interface doesn't actually need an implementation! This is because its tasks are straightforward enough that the EJB container can automatically provide the implementation.

The remote interface, however, needs an implementation which is supplied by the EJB programmer.

Bean Implementation , like Session Bean or Entity bean will have all the business methods and actual bulk of the code

/*
----------------------------------------------------------------------------------------------
Code by James Smith : james_smith73@yahoo.com
File Name : ManageCustBean.java
The codes is an Entity Bean to Manage Add/ Mod/ Del/ View/ View Many,  Operations
----------------------------------------------------------------------------------------------
*/

package EJB.ManageCust;

import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
import javax.ejb.*;

public class ManageCustBean implements EntityBean 
{
  // Initialisation of Varibles  ------------------------------------------------ 
  private String CustId;
  private String CustName;
  private String CustPh;
  private String CustPlan;

  private EntityContext ctx;

 private DataSource ds;
 private String dbName = "jdbc/Cloudscape"; 
 private Connection con;

 // Basic Getter and Setter Methods ---------------------------------------------- 
 public void setCustId(String CustId) 
 {
  this.CustId = CustId; // Remember the Remote Interface Above ? --------------------- 
 } 
 public String getCustId() 
 {
  return this.CustId; // Remember the Remote Interface Above ? --------------------- 
 }
 public void setCustName(String CustName) 
 {
  this.CustName = CustName;
 } 
 public String getCustName() 
 {
  return this.CustName;
 } 
 public void setCustPh(String CustPh) 
 {
  this.CustPh = CustPh;
 } 
 public String getCustPh() 
 {
  return this.CustPh;
 }
 public void setCustPlan(String CustPlan) 
 {
  this.CustPlan = CustPlan;
 } 
 public String getCustPlan() 
 {
  return this.CustPlan;
 }      

 // EJB Create --------------------------------------------------------------------- 
 // Connects to Database here we need to write Insert query ----------------------
 
 public String ejbCreate(String CustId, String CustName, String CustPh, String CustPlan) 
 throws CreateException 
 {
 System.out.println("Inside ejbCreate ------------------------------  ");	
  if (CustId == null) 
  {
   throw new CreateException("The CustId  is required.");
  }  
  else
  {
   // Insert Record ------------------------------------------------
   insertCustomerData (CustId, CustName, CustPh, CustPlan);		 	
  }  	
  this.CustId = CustId;
  this.CustName = CustName;
  this.CustPh = CustPh;
  this.CustPlan = CustPlan;	 
  return CustId;
} 

 // EJB ejbPostCreate -------------------------------------------------------- 
 public void ejbPostCreate(String CustId, String CustName, String CustPh, String CustPlan) 
 {
  System.out.println("Inside ejbPostCreate -------------------------------------------- ");
 }

 // EJB setEntityContext --------------------------------------------------- 
 public void setEntityContext(EntityContext context) 
 {
  System.out.println("Inside setEntityContext ----------------------------------------  ");
  this.ctx = context;
  try 
  {
   InitialContext initial = new InitialContext();
   ds = (DataSource)initial.lookup(dbName);
  } 
  catch (NamingException ne) 
  {
    throw new EJBException(ne);
  } 
}

 // EJB unsetEntityContext --------------------------------------------------------- 
 public void unsetEntityContext() 
 {
  System.out.println("Inside unsetEntityContext ------------------------------------  ");
  ctx = null;
 }
 
 // EJB ejbActivate ------------------------------------------------------------------- 
 public void ejbActivate() 
 {
  System.out.println("Inside ejbActivate --------------------------------------------  ");
  CustId = (String)ctx.getPrimaryKey();
 }
  
 // EJB ejbPassivate ------------------------------------------------------------------- 
 public void ejbPassivate() 
 {
  System.out.println("Inside ejbPassivate ----------------------------------------- ");
  CustId = null;
 }
  
 // EJB ejbLoad ----------------------------------------------------------------------- 
 // Used for Select Statement --------------------------------------------------------------- 
 public void ejbLoad() 
 {
  System.out.println("Inside ejbLoad ------------------------------------------  ");
  dataLoad ();
 }
  
 // EJB ejbStore --------------------------------------------------------------------- 
 // Used for Update Queries into the database -------------------------------------------
 public void ejbStore() 
 {
  System.out.println("Inside ejbStore ---------------------------------------------------  ");
  dataStore();
 }
 
 // EJB ejbRemove --------------------------------------------------------------------- 
 //Used for Delete Queries -------------------------------------------------------------------
 public void ejbRemove() 
 {
  System.out.println("Inside ejbRemove ----------------------------------------- ");
  dataRemove();
 } 
  
 // EJB ejbFindByPrimaryKey -------------------------------------------------------
 // Used for Select Query single record ---------------------------------------------------
 public String ejbFindByPrimaryKey(String primaryKey) throws FinderException 
 {
  System.out.println("Inside ejbFindByPrimaryKey -----------------------------------------  ");
  primaryKey = findData(primaryKey);
  return primaryKey;
 }

 // EJB ejbFindInRange ------------------------------------------------------------
// Used for Select many Records in Range 
 public Collection ejbFindInRange(int lowerLimit, int upperLimit) throws FinderException 
 {
  System.out.println("Inside ejbFindInRange ---------------------------------------------  ");
  try 
  {
   String sqlStmt = "SELECT CustId, CustName, CustPh,  CustPlan from custdata WHERE CustId BETWEEN ? AND ?";
   System.out.println("sqlStmt is : "+sqlStmt);
   con = ds.getConnection();
   PreparedStatement stmt = con.prepareStatement(sqlStmt);
   stmt.setInt(1, lowerLimit);
   stmt.setInt(2, upperLimit);
   ResultSet rs = stmt.executeQuery();
  ArrayList list = new ArrayList();
  while (rs.next()) 
  {
   String id = rs.getString(1);
   System.out.println("id is : "+id);
   list.add(id);
  } 
  stmt.close();
  return list;
 } 
 catch (SQLException sqle) 
 {
  throw new EJBException(sqle);
 } 
 finally 
 {
  try 
  {
   if (con != null) 
   {
    con.close();
   }
 } 
 catch (SQLException sqle) {}
 }
} 

// User Defined Methods -------------------------------------------------------------
// Since i did not wanted to write too much codes inside the default EJB methods like
// ejbCreate etc , i am defining my own which are called from those methods -----------

 public void insertCustomerData (String CustId, String CustName, String CustPh, String CustPlan)
 {
  System.out.println("Inside  insertCustomerData --------------------------------------------------------");
  System.out.println("CustId is : "+CustId);
  System.out.println("CustName is : "+CustName);
  System.out.println("CustPh is : "+CustPh);
  System.out.println("CustPlan is : "+CustPlan);
  try 
  {
   String sqlStmt = "INSERT INTO custdata VALUES ( ? , ? , ? , ? )";
   System.out.println("sqlStmt is : "+sqlStmt);
   con = ds.getConnection();
   PreparedStatement stmt = con.prepareStatement(sqlStmt);
   stmt.setString(1, CustId);
   stmt.setString(2, CustName);
   stmt.setString(3, CustPh);
   stmt.setString(4, CustPlan);
   stmt.executeUpdate();
   stmt.close();
 } 
 catch (SQLException sqle) 
 {
   throw new EJBException(sqle);
 } 
finally 
 {
  try 
  {          
   if (con != null) 
   {
    con.close();
   }
  } catch (SQLException sqle) {}
 }
}   

 public void dataLoad ()
 {
  System.out.println("Inside dataLoad -------------------------------------------------------------------  ");
  try 
  {
   String sqlStmt = "SELECT CustId, CustName, CustPh,  CustPlan FROM custdata WHERE CustId = ? ";
   System.out.println("sqlStmt is : "+sqlStmt);
   con = ds.getConnection();
   PreparedStatement stmt = con.prepareStatement(sqlStmt);
   stmt.setString(1, CustId);
   ResultSet rs = stmt.executeQuery();
   if (rs.next()) 
   {
    this.CustId = rs.getString("CustId");
    this.CustName = rs.getString("CustName");
    this.CustPh = rs.getString("CustPh");
    this.CustPlan = rs.getString("CustPlan");
    System.out.println("CustName is : "+CustName+" For Customer ID "+CustId);
    stmt.close();
  } 
  else 
  {
   stmt.close();
   throw new NoSuchEntityException("No Entity for Customer Id " + CustId);
  } 
 } 
 catch (SQLException sqle) 
 {
  throw new EJBException(sqle);
 } 
 finally 
 {
  try 
  {
    if (con != null) 
    {
     con.close();
    }
  }  catch (SQLException sqle) {}
}
}

public void dataStore()
{
 System.out.println("Inside dataStore ------------------------------------------  ");
 try 
 {
  con = ds.getConnection();
  String sqlStmt = "UPDATE custdata SET  CustName = ?,  CustPh = ?, CustPlan = ? WHERE CustId = ?";
  System.out.println("sqlStmt is : "+sqlStmt);       
  PreparedStatement stmt = con.prepareStatement(sqlStmt);
  stmt.setString(1, CustName);
  stmt.setString(2, CustPh);
  stmt.setString(3, CustPlan);
  stmt.setString(4, CustId);	   	  
   if (stmt.executeUpdate() != 1) 
   {
     throw new EJBException("Object state could not be saved");
   } 
   stmt.close();	 	   
 } 
 catch (SQLException sqle) 
 {
  throw new EJBException(sqle);
 } 
 finally 
 {
  try 
  {
   if (con != null) 
   {
    con.close();
   }
  } 
  catch (SQLException sqle) {}
 }
}

public void dataRemove()
{
 try 
 {
  con = ds.getConnection();		
  String sqlStmt = "DELETE FROM custdata WHERE CustId = ? ";
  System.out.println("sqlStmt is : "+sqlStmt);        
  PreparedStatement stmt = con.prepareStatement(sqlStmt);
  stmt.setString(1, CustId);
  stmt.executeUpdate();
  stmt.close();
} 
catch (SQLException sqle) 
{
throw new EJBException(sqle);
} 
finally 
{
  try 
  {
   if (con != null) 
   {
    con.close();
   }
  } catch (SQLException sqle) {}
 }
}

public String findData(String primaryKey) throws FinderException 
{
 try 
 {
  String sqlStmt = "SELECT * FROM custdata WHERE CustId = ? ";
  System.out.println("sqlStmt is : "+sqlStmt);
  con = ds.getConnection();
  PreparedStatement stmt = con.prepareStatement(sqlStmt);
  stmt.setString(1, primaryKey);
  ResultSet rs = stmt.executeQuery();     
  if (!rs.next()) 
  {
   throw new ObjectNotFoundException();
  }
  rs.close();
  stmt.close();
  //return primaryKey;
 } 
 catch (SQLException sqle) 
 {
  throw new EJBException(sqle);
 } 
 finally 
 {
  try 
  {
   if (con != null) 
   {
    con.close();
   }
 } catch (SQLException sqle) {}
}
return primaryKey;
}
// End User Defined  ---------------------------------------------------------------------- 
}
  Saving and Compiling the EJB
Save All the 3 Files (ManageCustHome.java , ManageCustRemote.java & ManageCustBean.java) in E:\Phone\EJB\ManageCust\ Directory

Create a dir E:\Phone\EJB\bat and inside that dir, write a small batch file to compile our Java files.
you can aswell use notepad to write a batch file.
E:\Phone\bat> edit compcustbean.bat
cls
javac ..\EJB\ManageCust\*.java
set CPATH=.;D:\j2sdkee1.3.1\lib\j2ee.jar;
Save and Exit the batch file and run it, Hope it compiles successfully if it doesnt add j2ee.jar into ur classpath, please refer the first chapter about the classpath settings , incase u fail to compile. if u r able to compile then u can proceed further
  What Next => Available : YES
Chapter 5. Writing Client Codes to Access these EJBs
 Reach me!
   My Web URL : http://www.oocities.org/james_smith73
   If you like this article and/or code mailme or Join our small Group of Java Programmers ,
Till we meet next time BYE     

  Java, J2EE, J2SE and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc.
in the United States and other countries.