Please show me an example of an Entity Bean that accesses more than one database table, using BMP.

Asit Padhi

here is the total code of an entity bean that uses multiple table using BMP


package com.orillion.india.nds.ejb.entity;

/*Enterprise Bean instance can throw javax.ejb.EJBException or 
* java.lang.RuntimeException to its container to report that the invoked
* business method or callback method could not be completed because of an
* unexpected error (e.g. the instance failed to open a database connection).
*/
import java.rmi.RemoteException;
import javax.ejb.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.naming.*;

public class CableEntityBean implements javax.ejb.EntityBean {

	public		java.lang.Integer	cableId;
	public		java.lang.String	cabName;
	public		java.lang.String	cabType;
	public		java.lang.String	cabLongName;
	public		java.lang.Integer	vendorId;
	public		java.lang.String	partNum;
	public		java.lang.String	actualState;
	public		java.sql.Date		actualStateDate;
	public		java.lang.String	actualSubState;
	public 		java.util.Vector    conCat = new Vector();
	private 	EntityContext  		entityContext = null;
	private 	Connection 			con = null;
    private 	String 				dbName = "java:comp/env/jdbc/NidDB3.0";
   
	
	
	//Place your business methods here.
	
	public Integer getCableId(){
		return cableId;
	}
	public java.lang.String getCabName(){
		return cabName;
	}
	public java.lang.String getCabType(){
		return cabType;
	}
	public java.lang.String getCabLongName(){
		return cabLongName;
	}
	public java.lang.Integer getVendorId(){
		return vendorId;
	}
	public java.lang.String getPartNum(){
		return partNum;
	}
	public java.lang.String getActualState(){
		return actualState;
	}
	public java.sql.Date getActualStateDate(){
		return actualStateDate;
	}
	public java.lang.String getActualSubState(){
		return actualSubState;
	}
	public java.util.Vector getConCat() {	
		return conCat;
	}		
	public void  setAllValues(String  cabName,String cabType,String cabLongName,
		Integer vendorId,String partNum,String  actualState,
		java.sql.Date  actualStateDate,String actualSubState,Vector Concatenation){
		this.cabName = cabName;
		this.cabType = cabType;
		this.cabLongName = cabLongName;
		this.vendorId = vendorId;
		this.partNum = partNum;
		this.actualState = actualState;
		this.actualStateDate = actualStateDate;
		this.actualSubState = actualSubState;
		if(Concatenation !=null){
			this.conCat =Concatenation;
		}
			
	}
		
	public java.lang.Integer ejbCreate(java.lang.String cabName, java.lang.String cabType,
		java.lang.String cabLongName, java.lang.Integer vendorId, java.lang.String partNum, 
		java.lang.String actualState, java.sql.Date actualStateDate, 
		java.lang.String actualSubState,Vector conCatenation)	
		throws javax.ejb.CreateException
	{
		this.cableId = getCableIdFromDB();
		this.cabName = cabName;
		this.cabType = cabType;
		this.cabLongName = cabLongName;
		this.vendorId = vendorId;
		this.partNum = partNum;
		this.actualState = actualState;
		this.actualStateDate = actualStateDate;
		this.actualSubState = actualSubState;
		
						
		try {
		  
		  makeConnection();
		  	
          insertRow(cableId, cabName, cabType, cabLongName,
		vendorId, partNum, actualState, actualStateDate,
		actualSubState);
          if(conCatenation != null) {
          	this.conCat =conCatenation;
          	insertIntoConcatenation(cableId,conCatenation);
          }	
          //System.out.println("able to ceate record" +this.cableId + this.cabType );
       } catch (Exception ex) {
           throw new EJBException("ejbCreate: " + 
              ex.getMessage());
       }
        finally {
        	
        	closeConnection();	
        }	
		
		return cableId ;
	}
	
	public void  ejbPostCreate(java.lang.String cabName, java.lang.String cabType, 
		java.lang.String cabLongName, java.lang.Integer vendorId, java.lang.String partNum, 
		java.lang.String actualState, java.sql.Date actualStateDate, 
		java.lang.String actualSubState, Vector conCatenation)	
		throws javax.ejb.CreateException
	{
	}
	
	//FindByPK method
	public Integer ejbFindByPrimaryKey(Integer primaryKey)
		throws javax.ejb.FinderException
	{
		
		try {
			
		 makeConnection();	
         if (selectByPrimaryKey(primaryKey)) {
         	return primaryKey;
         }
         else {
            throw new ObjectNotFoundException
               ("Row for id " + primaryKey + " not found.");
         }
       } catch (Exception ex) {
           throw new EJBException("ejbFindByPrimaryKey: " + ex.getMessage());
       }
       finally {
       	closeConnection();
       }	
			
	}
	
	//Implementing EntityBeanInterface methods.....
	public void setEntityContext(EntityContext entityContext)
		throws javax.ejb.EJBException, java.rmi.RemoteException
	{
		this.entityContext = entityContext;
		
           	
	}
	
	public void unsetEntityContext()
		throws javax.ejb.EJBException, java.rmi.RemoteException
	{
		this.entityContext = null;
		
	}
	
		//Remove Methods....
	public void ejbRemove()
		throws java.rmi.RemoteException, javax.ejb.EJBException, javax.ejb.RemoveException
	{
		try {
			makeConnection();
			
        	deleteRow(cableId);
        } catch (Exception ex) {
           throw new EJBException("ejbRemove: " + ex.getMessage());
       }
       finally {
       	  closeConnection();
       }	
	}
	
	public void ejbActivate()
		throws javax.ejb.EJBException, java.rmi.RemoteException
	{
		cableId = (Integer)entityContext.getPrimaryKey();
	}
	
	public void ejbPassivate()
		throws javax.ejb.EJBException, java.rmi.RemoteException
	{
		closeConnection();
		cableId =null;
	}
	
	public void ejbLoad()
		throws javax.ejb.EJBException, java.rmi.RemoteException
	{
		try {
		 makeConnection();  	
         loadRow();
       } catch (Exception ex) {
           throw new EJBException("ejbLoad: " + ex.getMessage());
       }
       finally {
       		closeConnection();
       }	
	}
	
	public void ejbStore()
		throws javax.ejb.EJBException, java.rmi.RemoteException
	{
		try {
		 makeConnection();	
         storeRow();
       } catch (Exception ex) {
           throw new EJBException("ejbStore: " + 
              ex.getMessage());
       }
       finally {
       		closeConnection();
       }	
	}
	//-----end of implementation-----------
	//Serialization of BeanObject is to be done here.....//
	private void writeObject(java.io.ObjectOutputStream out)
		throws java.io.IOException
	{
		//write non-serializable attributes here...

		out.defaultWriteObject();
	}

	private void readObject(java.io.ObjectInputStream in)
		throws java.io.IOException, ClassNotFoundException
	{
		//read non-serializable attributes here ...

		in.defaultReadObject();
	}
	// serialization done       ///
	
		/*********************** Database Routines *************************/

   private void makeConnection() throws NamingException, SQLException {

      InitialContext ic = new InitialContext();
      DataSource ds = (DataSource) ic.lookup(dbName);
      con =  ds.getConnection();
   }
   
   private void closeConnection()  {
	try {
   	 	con.close();
   	}catch(Exception e) {
   		//e.printStackTrace();
   	}  	
   }	

   private void insertRow (Integer cableId, String cabName, String cabType, String cabLongName,
		Integer vendorId,String partNum,
		String actualState, java.sql.Date actualStateDate, 
		String actualSubState) throws SQLException {
		  	
          String insertStatement =
                "insert into cable values ( ? , ? , ? , ?, ?, ?, ?, ?, ? )";
          PreparedStatement prepStmt = 
                con.prepareStatement(insertStatement);

          prepStmt.setInt(1, cableId.intValue());
          prepStmt.setString(2, cabName);
          prepStmt.setString(3,cabType);
          if(cabLongName !=null)  
          	prepStmt.setString(4, cabLongName);
          else 
          	prepStmt.setNull(4,Types.VARCHAR);
          prepStmt.setInt(5, vendorId.intValue());
          if(partNum !=null) 
          	prepStmt.setString(6, partNum);
          else 
          	prepStmt.setNull(6,Types.VARCHAR);
          prepStmt.setString(7, actualState);
          prepStmt.setDate(8, actualStateDate);
          prepStmt.setString(9, actualSubState);

          prepStmt.executeUpdate();
          //System.out.println("created the record" + cableId);
          prepStmt.close();
   }
   private void insertRowIntoConcat(int cabid, int cabConcatenate, 
		int position) throws SQLException	{
   	
   	String insertStatement =
                "insert into cableconcatenation values ( ? , ? , ?  )";
          PreparedStatement prepStmt = 
                con.prepareStatement(insertStatement);

          prepStmt.setInt(1, cabid);
          prepStmt.setInt(2,cabConcatenate);
          prepStmt.setInt(3, position);
          
          prepStmt.executeUpdate();
          prepStmt.close();
   			
   }
   private void deleteRow(Integer cableId) throws SQLException {

      String deleteStatement =
            "delete from cable where cableId = ? ";
      PreparedStatement prepStmt =
            con.prepareStatement(deleteStatement);

      prepStmt.setInt(1, cableId.intValue());
      prepStmt.executeUpdate();
      prepStmt.close();
   }
   
   private void deleteRowFromConcat(Integer cabConId) throws SQLException {

      String deleteStatement =
            "delete from cableconcatenation where cabconcatenate = ? ";
      PreparedStatement prepStmt =
            con.prepareStatement(deleteStatement);

      prepStmt.setInt(1, cabConId.intValue());
      prepStmt.executeUpdate();
      prepStmt.close();
   }

   private boolean selectByPrimaryKey(Integer primaryKey) 
      throws SQLException {

      String selectStatement =
            "select cableId " +
            "from cable where cableId = ? ";
      PreparedStatement prepStmt =
            con.prepareStatement(selectStatement);
      prepStmt.setInt(1, primaryKey.intValue());

      ResultSet rs = prepStmt.executeQuery();
      boolean result = rs.next();
      prepStmt.close();
      return result;
   }

   private void loadRow() throws SQLException {

      String selectStatement =
            "select cabName,cabType,cabLongName,vendorId,partNum,actualState,actualStateDate,actualSubState " +
            "from cable where cableId = ? ";
            
      PreparedStatement prepStmt = 
            con.prepareStatement(selectStatement);
      
      prepStmt.setInt(1,this.cableId.intValue());
      
      ResultSet rs = prepStmt.executeQuery();
      if (rs.next()) {
         this.cabName   = rs.getString(1);
         this.cabType     = rs.getString(2);
         this.cabLongName = rs.getString(3);
         this.vendorId = new Integer(rs.getInt(4));
         this.partNum = rs.getString(5);
         this.actualState     = rs.getString(6);
         this.actualStateDate = rs.getDate(7);
         this.actualSubState  = rs.getString(8);
         prepStmt.close();
      }
      
      else {
         prepStmt.close();
         throw new NoSuchEntityException("Row for id " + cableId +
            " not found in database.");
      }
      
      String selectStatement1 = 
	"select cabId from CableConcatenation where cabconcatenate = ? order by listposition ";
      PreparedStatement prepStmt1 = con.prepareStatement(selectStatement1);
      prepStmt1.setInt(1,this.cableId.intValue());
      ResultSet rs1 = prepStmt1.executeQuery();
      
      while (rs1.next()) {
      	 this.conCat.addElement(new Integer(rs1.getInt(1)));
      }
      if(!(conCat.size() > 0)) this.conCat =new Vector();
      
      prepStmt1.close();      
      
   }


   private void storeRow() throws SQLException {

      String updateStatement =
            "update cable set cabName =  ? ,cabType = ? ,cabLongName = ?, " +
            "vendorId = ? , partNum =?, actualState = ?,actualStateDate=?, actualSubState=? " +
            "where cableId= ?";
      PreparedStatement prepStmt = 
            con.prepareStatement(updateStatement);

      prepStmt.setString(1, cabName);
      prepStmt.setString(2, cabType);
      if(cabLongName !=null)  
        prepStmt.setString(3, cabLongName);
      else 
        prepStmt.setNull(3,Types.VARCHAR);
      prepStmt.setInt(4, vendorId.intValue());
      
      if(partNum !=null) 
      	prepStmt.setString(5, partNum);
      else 
      	prepStmt.setNull(5,Types.VARCHAR);	
      
      prepStmt.setString(6, actualState);
      prepStmt.setDate(7, actualStateDate);
      prepStmt.setString(8, actualSubState);
      prepStmt.setInt(9, cableId.intValue());
      int rowCount = 0;
      try {
      	rowCount = prepStmt.executeUpdate();
      	
      	if(conCat.size()> 0) {
      		deleteRowFromConcat(cableId);
      		insertIntoConcatenation(cableId,conCat);
      	}
      	
      } catch (SQLException e) {
      	//e.printStackTrace();
      }
      prepStmt.close();

      if (rowCount == 0) {
         throw new EJBException("Storing row for id " + cableId + " failed.");
      }
   }
   
   private void insertIntoConcatenation(Integer cabid,Vector concatenation) throws SQLException {

    	for(int i=0; i < concatenation.size(); i++) {
    		Integer id =(Integer) concatenation.elementAt(i);
    		insertRowIntoConcat(id.intValue(),cabid.intValue(),i+1);
    	}	
    	
   }
   
   public Integer getCableIdFromDB() {
		int cableId =0;
		String query = "select cable_seq.nextval from dual";
		try {
			makeConnection();
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			rs.next();
        	cableId = rs.getInt(1);
        }catch(Exception ex){
        	//System.out.println(ex.getMessage());
        }	
        finally {
        	closeConnection();
        }	
        return (new Integer(cableId));

	}		
    
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact