+

Search Tips   |   Advanced Search

Example: Handling connection exceptions for BMP beans in container-managed database transactions


The following code sample demonstrates how to roll back transactions and issue exceptions to the bean client in cases of stale connection exceptions.

//===================START_PROLOG======================================

//

//   5630-A23, 5630-A22, 
//   (C) COPYRIGHT International Business Machines Corp. 2005,2008

//   All Rights Reserved

//   Licensed Materials - Property of IBM

//   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;
 import java.util.*;
 import javax.ejb.*;
 import java.sql.*;
 import javax.sql.*;
 import javax.ejb.*;
 import javax.naming.*;
 import com.ibm.websphere.rsadapter.WSCallHelper;

/**
 * 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 
 * ejbActivate calls getDS(), which performs the 
 * JNDI lookup for the datasource.
 */ public void ejbActivate() {
       getDS();
}
/**
 * ejbCreate method for a BMP entity bean
 * @return WebSphereSamples.ConnPool.EmployeeBMPKey
 * @param key WebSphereSamples.ConnPool.EmployeeBMPKey
 * @exception javax.ejb.CreateException 
 */ 
public WebSphereSamples.ConnPool.EmployeeBMPKey ejbCreate(String empNo,  String firstName, String lastName, String middleInit, int edLevel) throws  javax.ejb.CreateException {

   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 (SQLException se)
   {
      if (WSCallHelper.getDataStoreHelper(ds).isConnectionError(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("Connection is stale: " +  se.getMessage());
         throw new CreateException(se.getMessage());
      } 
      else
      {
         System.out.println("SQL Exception during get connection or process SQL: " +
                          se.getMessage());
         throw new CreateException(se.getMessage());
      } 


finally { // Always close the connection in a finally statement to ensure proper // closure in all cases. Closing the connection does not close an // 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 javax.ejb.FinderException */ public WebSphereSamples.ConnPool.EmployeeBMPKey ejbFindByPrimaryKey(WebSphereSamples.ConnPool.EmployeeBMPKey primaryKey) javax.ejb.FinderException { loadByEmpNo(primaryKey.empNo); return primaryKey; } /** * ejbLoad method */ public void ejbLoad() { try { EmployeeBMPKey pk = (EmployeeBMPKey) entityContext.getPrimaryKey(); loadByEmpNo(pk.empNo); } catch (FinderException fe) { throw new EJBException("Cannot load Employee state from database."); } } /** * ejbPassivate method */ public void ejbPassivate() {} /** * ejbPostCreate method for a BMP entity bean * @param key WebSphereSamples.ConnPool.EmployeeBMPKey */ public void ejbPostCreate(String empNo, String firstName, String lastName, String middleInit, int edLevel) {} /** * ejbRemove method * @exception javax.ejb.RemoveException */ public void ejbRemove() throws 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 EJBException("Cannot remove employee: " + empNo); } } catch (SQLException se) { if (WSCallHelper.getDataStoreHelper(ds).isConnectionError(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("Connection is stale: " + se.getMessage()); throw new EJBException(se.getMessage()); } else { System.out.println("SQL Exception during get connection or process SQL: " + se.getMessage()); throw new EJBException(se.getMessage()); }

finally { // Always close the connection in a finally statement to ensure proper // closure in all cases. Closing the connection does not close an // 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 { 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 (SQLException se) { if (WSCallHelper.getDataStoreHelper(ds).isConnectionError(se)) { // This exception indicates that the connection to the database is no longer valid. // Roll back the transaction, and throw an exception to the client indicating they // can retry the transaction if desired. System.out.println("Connection is stale: " + se.getMessage()); throw new FinderException(se.getMessage()); } else { System.out.println("SQL Exception during get connection or process SQL: " + se.getMessage()); throw new FinderException(se.getMessage()); } } finally { // Always close the connection in a finally statement to ensure // proper closure in all cases. Closing the connection does not // close an 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 */ public void setEntityContext(javax.ejb.EntityContext ctx) { 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 */ public void unsetEntityContext() { entityContext = null; } }

//===================START_PROLOG======================================

//

//   5630-A23, 5630-A22, 
//   (C) COPYRIGHT International Business Machines Corp. 2002,2008

//   All Rights Reserved

//   Licensed Materials - Property of IBM

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

//===================START_PROLOG======================================

//

//   5630-A23, 5630-A22, 
//   (C) COPYRIGHT International Business Machines Corp. 2002,2008

//   All Rights Reserved

//   Licensed Materials - Property of IBM

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

//===================START_PROLOG======================================

//

//   5630-A23, 5630-A22, 
//   (C) COPYRIGHT International Business Machines Corp. 2002,2008

//   All Rights Reserved

//   Licensed Materials - Property of IBM

//   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 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();





 

Related


Administrative console buttons
Administrative console page features