Example: Entity bean with BMP and container managed transaction

 

package WebSphereSamples.ConnPool;

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


/**
 * This is an Entity Bean class with five BMP fields
 * String firstName, String lastName, String middleInit
 * String empNo, int edLevel
 */

public class EmployeeBMPBean implements EntityBean 
{
    private javax.ejb.EntityContext entityContext = null;
    final static long serialVersionUID = 3206093459760846163L;

    private java.lang.String firstName;
    private java.lang.String lastName;
    private String middleInit;
    private javax.sql.DataSource ds;
    private java.lang.String empNo;
    private int edLevel;


    /**
     * ejbActivate method 
     * @exception java.rmi.RemoteException
     * ejbActivate calls getDS(), which perfoms the 
     * JNDI lookup for the datasource.
     */
    public void ejbActivate() throws java.rmi.RemoteException 
    {
        getDS();
    }

    /**
     * ejbCreate method for a BMP entity bean
     * @return WebSphereSamples.ConnPool.EmployeeBMPKey
     * @param key WebSphereSamples.ConnPool.EmployeeBMPKey
     * @exception javax.ejb.CreateException 
     * @exception java.rmi.RemoteException 
     */
public WebSphereSamples.ConnPool.EmployeeBMPKey ejbCreate(String empNo, String firstName, String lastName, String middleInit, int edLevel) throws javax.ejb.CreateException, java.rmi.RemoteException {

   Connection conn = null;
   PreparedStatement ps = null;
    
   if (ds == null) getDS();
        
   this.empNo = empNo;
   this.firstName = firstName;
   this.lastName = lastName;
   this.middleInit = middleInit;
   this.edLevel = edLevel;

   String sql = "insert into Employee (empNo, firstnme, midinit, lastname, edlevel) values (?,?,?,?,?)";
        
   try {
      conn = ds.getConnection();
      ps = conn.prepareStatement(sql);            
      ps.setString(1, empNo);
      ps.setString(2, firstName);
      ps.setString(3, middleInit);
      ps.setString(4, lastName);
      ps.setInt(5, edLevel);
        
 if (ps.executeUpdate() != 1){
         System.out.println("ejbCreate Failed to add user.");
         throw new CreateException("Failed to add user.");
      }
   } 
   catch (com.ibm.websphere.ce.cm.StaleConnectionException se) {

// This exception indicates that the connection to the database is no longer valid.
// Rollback the transaction, and throw an exception to the client indicating they
// can retry the transaction if desired.

System.out.println("Stale Connection Exception during get connection or process SQL: " +  se.getMessage());
      throw new CreateException(se.getMessage());
   } 
   catch (SQLException sq) {
      System.out.println("SQL Exception during get connection or process SQL: " +
                          sq.getMessage());
   throw new CreateException(sq.getMessage());
   } 
   finally {
      // Always close the connection in a finally statement to ensure proper 
      // closure in all cases. Closing the connection does not close and 
      // actual connection, but releases it back to the pool for reuse.
  if  ps(!= null) {
         try {
            ps.close();
         } 
         catch  Exception(e) {
            System.out.println("Close Statement Exception: " + e.getMessage());
         }
      }
      if (conn != null) {
         try {
            conn.close();
         } 
         catch  Exception(e) {
            System.out.println("Close connection exception: " + e.getMessage());
         }
      }
   }
   return new EmployeeBMPKey(this.empNo);
}

/**
 * ejbFindByPrimaryKey method
 * @return WebSphereSamples.ConnPool.EmployeeBMPKey
 * @param primaryKey WebSphereSamples.ConnPool.EmployeeBMPKey
 * @exception java.rmi.RemoteException
 * @exception javax.ejb.FinderException
 */
public WebSphereSamples.ConnPool.EmployeeBMPKey ejbFindByPrimaryKey(WebSphereSamples.ConnPool.EmployeeBMPKey primaryKey) throws java.rmi.RemoteException, javax.ejb.FinderException {
    loadByEmpNo(primaryKey.empNo);
    return primaryKey;
}

/**
 * ejbLoad method
 * @exception java.rmi.RemoteException
 */
public void ejbLoad() throws java.rmi.RemoteException {
    try {
        EmployeeBMPKey pk = (EmployeeBMPKey) entityContext.getPrimaryKey();
        loadByEmpNo(pk.empNo);
    } catch (FinderException fe) {
        throw new RemoteException("Cannot load Employee state from database.");
    }    
}

/**
 * ejbPassivate method
 * @exception java.rmi.RemoteException
 */
public void ejbPassivate() throws java.rmi.RemoteException {}

/**
 * ejbPostCreate method for a BMP entity bean
 * @param key WebSphereSamples.ConnPool.EmployeeBMPKey
 * @exception java.rmi.RemoteException
 */
public void ejbPostCreate(String empNo, String firstName, String lastName, String middleInit, int edLevel) throws java.rmi.RemoteException {}

/**
 * ejbRemove method
 * @exception java.rmi.RemoteException
 * @exception javax.ejb.RemoveException
 */
public void ejbRemove() throws java.rmi.RemoteException, javax.ejb.RemoveException {
    
   if (ds == null) 
      GetDS();

   String sql = "delete from Employee where empNo=?";
   Connection con = null;
   PreparedStatement ps = null;
 try {            
      con = ds.getConnection();                                    
      ps = con.prepareStatement(sql);                        
      ps.setString(1, empNo);
      if (ps.executeUpdate() != 1){
         throw new RemoteException("Cannot remove employee: " + empNo);
      }
   } 
   catch (com.ibm.websphere.ce.cm.StaleConnectionException se) {

// This exception indicates that the connection to the database is no longer valid.
// Rollback the transaction, and throw an exception to the client indicating they
// can retry the transaction if desired.

System.out.println("Stale Connection Exception during get connection or process SQL: " + se.getMessage());
      throw new RemoteException(se.getMessage());
   } 
   catch (SQLException sq) {
      System.out.println("SQL Exception during get connection or process SQL: " +
                          sq.getMessage());
      throw new RemoteException(sq.getMessage());   
   } 
   finally {
      // Always close the connection in a finally statement to ensure proper 
      // closure in all cases. Closing the connection does not close and
      // actual connection, but releases it back to the pool for reuse.
      if  ps(!= null) {
         try {
            ps.close();
         } 
         catch  Exception(e) {
            System.out.println("Close Statement Exception: " + e.getMessage());
         }
      }
      if (con != null) {
         try {
            con.close();
         } 
         catch  Exception(e) {
            System.out.println("Close connection exception: " + e.getMessage());
         }
      }
   }
}
 try {            
      con = ds.getConnection();                                    
      ps = con.prepareStatement(sql);                        
      ps.setString(1, empNo);
      if (ps.executeUpdate() != 1){
         throw new RemoteException("Cannot remove employee: " + empNo);
      }
   } 
   catch (com.ibm.websphere.ce.cm.StaleConnectionException se) {

// This exception indicates that the connection to the database is no longer valid.
// Rollback the transaction, and throw an exception to the client indicating they
// can retry the transaction if desired.

System.out.println("Stale Connection Exception during get connection or process SQL: " + se.getMessage());
      throw new RemoteException(se.getMessage());
   } 
   catch (SQLException sq) {
      System.out.println("SQL Exception during get connection or process SQL: " +
                          sq.getMessage());
      throw new RemoteException(sq.getMessage());   
   } 
   finally {
      // Always close the connection in a finally statement to ensure proper 
      // closure in all cases. Closing the connection does not close and
      // actual connection, but releases it back to the pool for reuse.
      if  ps(!= null) {
         try {
            ps.close();
         } 
         catch  Exception(e) {
            System.out.println("Close Statement Exception: " + e.getMessage());
         }
      }
      if (con != null) {
         try {
            con.close();
         } 
         catch  Exception(e) {
            System.out.println("Close connection exception: " + e.getMessage());
         }
      }
   }
}

} 
   catch (com.ibm.websphere.ce.cm.StaleConnectionException se) {

// This exception indicates that the connection to the database is no longer valid.
// Rollback the transaction, and throw an exception to the client indicating they
// can retry the transaction if desired.

System.out.println("Stale Connection Exception during get connection or process SQL: " + se.getMessage());
      throw new RemoteException(se.getMessage());
   } 
   catch (SQLException sq) {

      System.out.println("SQL Exception during get connection or process SQL: " +
                          sq.getMessage());

      throw new RemoteException(sq.getMessage());
   } 
   finally {
      // Always close the connection in a finally statement to ensure proper 
      // closure in all cases. Closing the connection does not close and 
      // actual connection, but releases it back to the pool for reuse.
      if  ps(!= null) {
         try {
            ps.close();
         } 
         catch  Exception(e) {
            System.out.println("Close Statement Exception: " + e.getMessage());
         }
      }
      if (con != null) {
         try {
            con.close();
         } 
         catch  Exception(e) {
            System.out.println("Close connection exception: " + e.getMessage());
         }
      }
   }
}

/**
 * Get the employee's edLevel
 * Creation date: (4/20/2001 3:46:22 PM)
 * @return int
 */
public int getEdLevel() {
    return edLevel;
}

/**
 * getEntityContext method
 * @return javax.ejb.EntityContext
 */
public javax.ejb.EntityContext getEntityContext() {
    return entityContext;
}

/**
 * Get the employee's first name
 * Creation date: (4/19/2001 1:34:47 PM)
 * @return java.lang.String
 */
public java.lang.String getFirstName() {
    return firstName;
}

/**
 * Get the employee's last name
 * Creation date: (4/19/2001 1:35:41 PM)
 * @return java.lang.String
 */
public java.lang.String getLastName() {
    return lastName;
}

/**
* get the employee's middle initial
 * Creation date: (4/19/2001 1:36:15 PM)
 * @return char
 */
public String getMiddleInit() {
    return middleInit;
}

/**
 * Lookup the DataSource from JNDI
 * Creation date: (4/19/2001 3:28:15 PM)
 */
private void getDS() {
    try {
    // Note the new Initial Context Factory interface available in WebSphere 4.0        
        Hashtable parms = new Hashtable();
        parms.put(Context.INITIAL_CONTEXT_FACTORY, 
                "com.ibm.websphere.naming.WsnInitialContextFactory");
        InitialContext ctx = new InitialContext(parms);
        // Perform a naming service lookup to get the DataSource object.
        ds = (DataSource)ctx.lookup("java:comp/env/jdbc/SampleDB");
    } 
       catch  Exception(e) {
        System.out.println("Naming service exception: " + e.getMessage());
        e.printStackTrace();
    }
}

/**
 * Load the employee from the database
 * Creation date: (4/19/2001 3:44:07 PM)
 * @param empNo java.lang.String
 */
private void loadByEmpNo(String empNoKey) throws javax.ejb.FinderException{

    String sql = "select empno, firstnme, midinit, lastname, edLevel from employee where empno = ?";
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    if (ds == null) getDS();
    
    try {
// Get a Connection object conn using the DataSource factory.
           conn = ds.getConnection();
          // Run DB query using standard JDBC coding.
        ps = conn.prepareStatement(sql);
        ps.setString(1, empNoKey);
        rs = ps.executeQuery();
        if (rs.next()) {
            empNo= rs.getString(1);
            firstName=rs.getString(2);
            middleInit=rs.getString(3);
            lastName=rs.getString(4); 
            edLevel=rs.getInt(5);
        } 
             else {
                throw new ObjectNotFoundException("Cannot find employee number " +
                                                   empNoKey);
             }
      } 
      catch (com.ibm.websphere.ce.cm.StaleConnectionException se) {

// This exception indicates that the connection to the database is no longer valid.
// Rollback the transaction, and throw an exception to the client indicating they
// can retry the transaction if desired.

System.out.println("Stale Connection Exception during get connection or process SQL: " + se.getMessage());
         throw new FinderException(se.getMessage());
      } 
      catch (SQLException sq) {
System.out.println("SQL Exception during get connection or process SQL: " +
                   sq.getMessage());
         throw new FinderException(sq.getMessage());
      } 
      finally {
        // Always close the connection in a finally statement to ensure proper 
        // closure in all cases. Closing the connection does not close and 
        // actual connection, but releases it back to the pool for reuse.
         if (rs != null) {
            try {
               Rs.close();
            } 
            catch  Exception(e) {
               System.out.println("Close Resultset Exception: " + e.getMessage());
            }
         }
         if  ps(!= null) {
            try {
               ps.close();
            } 
            catch  Exception(e) {
               System.out.println("Close Statement Exception: " + e.getMessage());
            }
         }
         if (conn != null) {
            try {
               conn.close();
            } 
            catch  Exception(e) {
               System.out.println("Close connection exception: " + e.getMessage());
            }
        }
     }      
}

/**
 * set the employee's education level
 * Creation date: (4/20/2001 3:46:22 PM)
 * @param newEdLevel int
 */
public void setEdLevel(int newEdLevel) {
    edLevel = newEdLevel;
}

/**
 * setEntityContext method
 * @param ctx javax.ejb.EntityContext
 * @exception java.rmi.RemoteException
 */
public void setEntityContext(javax.ejb.EntityContext ctx) throws java.rmi.RemoteException {
    entityContext = ctx;
}

/**
 * set the employee's first name
 * Creation date: (4/19/2001 1:34:47 PM)
 * @param newFirstName java.lang.String
 */
public void setFirstName(java.lang.String newFirstName) {
    firstName = newFirstName;
}

/**
 * set the employee's last name
 * Creation date: (4/19/2001 1:35:41 PM)
 * @param newLastName java.lang.String
 */
public void setLastName(java.lang.String newLastName) {
    lastName = newLastName;
}

/**
 * set the employee's middle initial
 * Creation date: (4/19/2001 1:36:15 PM)
 * @param newMiddleInit char
 */
public void setMiddleInit(String newMiddleInit) {
    middleInit = newMiddleInit;
}

/**
 * unsetEntityContext method
 * @exception java.rmi.RemoteException
 */
public void unsetEntityContext() throws java.rmi.RemoteException {
    entityContext = null;
}
}

//===================START_PROLOG======================================
//
//   5630-A23, 5630-A22,
//   (C) COPYRIGHT International Business Machines Corp. 2002
//   All Rights Reserved
//   Licensed Materials - Property of IBM
//   US Government Users Restricted Rights - Use, duplication or
//   disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//
//   IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
//   ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//   PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
//   CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
//   USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
//   OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
//   OR PERFORMANCE OF THIS SOFTWARE.
//
//===================END_PROLOG========================================

package WebSphereSamples.ConnPool;


/**
 * This is a Home interface for the Entity Bean
 */
public interface EmployeeBMPHome extends javax.ejb.EJBHome {


/**
 * 
 * @return WebSphereSamples.ConnPool.EmployeeBMP
 * @param empNo java.lang.String
 * @param firstName java.lang.String
 * @param lastName java.lang.String
 * @param middleInit java.lang.String
 * @param edLevel int 
 */
WebSphereSamples.ConnPool.EmployeeBMP create(java.lang.String empNo, java.lang.String firstName, java.lang.String lastName, java.lang.String middleInit, int edLevel) throws javax.ejb.CreateException, java.rmi.RemoteException;

/**
 * findByPrimaryKey method comment
 * @return WebSphereSamples.ConnPool.EmployeeBMP
 * @param key WebSphereSamples.ConnPool.EmployeeBMPKey
 * @exception java.rmi.RemoteException
 * @exception javax.ejb.FinderException
 */
WebSphereSamples.ConnPool.EmployeeBMP findByPrimaryKey(WebSphereSamples.ConnPool.EmployeeBMPKey key) throws java.rmi.RemoteException, javax.ejb.FinderException;
}

//===================START_PROLOG======================================
//
//   5630-A23, 5630-A22,
//   (C) COPYRIGHT International Business Machines Corp. 2002
//   All Rights Reserved
//   Licensed Materials - Property of IBM
//   US Government Users Restricted Rights - Use, duplication or
//   disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//
//   IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
//   ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//   PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
//   CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
//   USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
//   OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
//   OR PERFORMANCE OF THIS SOFTWARE.
//
//===================END_PROLOG========================================

package WebSphereSamples.ConnPool;


/**
 * This is an Enterprise Java Bean Remote Interface
 */
public interface EmployeeBMP extends javax.ejb.EJBObject {


/**
 * 
 * @return int
  */
int getEdLevel() throws java.rmi.RemoteException;

/**
 * 
 * @return java.lang.String
 */
java.lang.String getFirstName() throws java.rmi.RemoteException;

/**
 * 
 * @return java.lang.String
 */
java.lang.String getLastName() throws java.rmi.RemoteException;

/**
 * 
 * @return java.lang.String
 */
java.lang.String getMiddleInit() throws java.rmi.RemoteException;

/**
 * 
 * @return void
 * @param newEdLevel int
 */
void setEdLevel(int newEdLevel) throws java.rmi.RemoteException;

/**
 * 
 * @return void
 * @param newFirstName java.lang.String
 */
void setFirstName(java.lang.String newFirstName) throws java.rmi.RemoteException;

/**
 * 
 * @return void
 * @param newLastName java.lang.String
 */
void setLastName(java.lang.String newLastName) throws java.rmi.RemoteException;

/**
 * 
 * @return void
 * @param newMiddleInit java.lang.String
 */
void setMiddleInit(java.lang.String newMiddleInit) throws java.rmi.RemoteException;
}





package WebSphereSamples.ConnPool;

/**
* This is a Primary Key Class for the Entity Bean
**/
public class EmployeeBMPKey implements java.io.Serializable { 
    public String empNo;
    final static long serialVersionUID = 3206093459760846163L;

/**
* EmployeeBMPKey() constructor 
*/
public EmployeeBMPKey()  {
}
/**
* EmployeeBMPKey(String key) constructor 
*/
public EmployeeBMPKey(String key)  {
    empNo = key;
}
/**
* equals method
* - user must provide a proper implementation for the equal method. The generated 
*   method assumes the key is a String object.
*/
public boolean equals  Object(o)  {
    if (o instanceof EmployeeBMPKey) 
        return empNo.equals(((EmployeeBMPKey)o).empNo);
    else
        return false;
}
/**
* hashCode method
* - user must provide a proper implementation for the hashCode method. The generated
*    method assumes the key is a String object.
*/
public int hashCode ()  {
    return empNo.hashCode();