Public null findByPrimaryKey

I get a weird error when I deploy an application on OC4J 904 Standalone
04/01/07 16:29:54 Error instantiating application 'ams2isyappl' at file:/D:/OC4J_904_PROD/j2ee/home/
applications/ams2isyappl.ear: Error initializing ejb-module; Exception No method matching 'public nu
ll findByPrimaryKey(java.lang.Integer)' found in null
Any clues on this, anybody.

I get a weird error when I deploy an application on OC4J 904 Standalone
04/01/07 16:29:54 Error instantiating application 'ams2isyappl' at file:/D:/OC4J_904_PROD/j2ee/home/
applications/ams2isyappl.ear: Error initializing ejb-module; Exception No method matching 'public nu
ll findByPrimaryKey(java.lang.Integer)' found in null
Any clues on this, anybody.

Similar Messages

  • Transfer object,  FindByPrimaryKey, session facade

    I would like to request help on coding a 'facade session' bean that invokes the FindByPrimaryKey method on a BMP entity bean, and how to put the returned values into a transfer object. I've been trying to modify the code provided in Sun's 'Duke's Bank Application' to accomplish this. Below is the code copied and pasted from Sun's session facade. 'accountIds' is a Collection that contains the values (customerId, balance, etc) of bank accounts which were retrieved with a FindBy method. AccountDetails produces a transfer object.
    try {
    Iterator i = accountIds.iterator();
    while (i.hasNext()) {
    Account account = (Account)i.next();
    AccountDetails accountDetails = account.getDetails();
    accountList.add(accountDetails);
    I was wondering how to accomplish the task of transfering values into a transfer object when invoking FindByPrimaryKey.
    I've taken a few stabs at it. My FindByPrimaryKey method doesn't throw any exceptions (as far as I can tell):
    try {
    Account account = accountHome.findByPrimaryKey(id);
    } catch (Exception ex) {
    throw new AccountNotFoundException("darn it - " + ex.getMessage());
    The error (which appears in the catalina log) occurs in the following section of code, which immediately follows the above:
    ArrayList myAccountDetails = new ArrayList();
    try {
    AccountDetails accountDetails = account.getDetails();
    myAccountDetails.add(accountDetails);
    } catch (RemoteException ex) {
    throw new EJBException("getDetails isn't working in AccountControllerBean: " + ex.getMessage());
    And here is the business method from Account:
    public AccountDetails getDetails() {
    return new AccountDetails(id, surname, firstname, balance);
    If any of the experts out there have spotted a mistake, I sure would be grateful for your help.
    James

    Thank you for your help. I think the ejbCreate method in the 'session facade' takes into account your advice:
    public void ejbCreate() {
    try {
    accountHome = EJBGetter.getAccountHome();
    } catch (Exception ex) {
    throw new EJBException("ejbCreate: " +
    ex.getMessage());
    account = null;
    accountId = null;
    I included your piece of code just the same to see if it would help anyway. Unfortunately the same error appeared in the catalina file.
    Also, there were error messages I hadn't noticed until now in the Verifier.
    One read:
    "No findByPrimaryKey method was found in home interface class [database.AccountHome]"
    The other:
    "No single argument findByPrimaryKey was found in home interface class [database.AccountHome]"
    Here is the method in the implementation class of the entity bean:
    public String ejbFindByPrimaryKey(String primaryKey)
    throws FinderException {
    boolean result;
    try {
    result = selectById(primaryKey);
    } catch (Exception ex) {
    throw new EJBException("ejbFindByPrimaryKey: " +
    ex.getMessage());
    if (result) {
    return primaryKey;
    else {
    throw new ObjectNotFoundException
    ("Row for id " + id + " not found.");
    Below is the 'selectById' method that it invokes:
    private boolean selectById(String primaryKey)
    throws SQLException {
    makeConnection();
    String selectStatement =
    "select id " +
    "from accountTable where id = ? ";
    PreparedStatement prepStmt =
    con.prepareStatement(selectStatement);
    prepStmt.setString(1, primaryKey);
    ResultSet rs = prepStmt.executeQuery();
    boolean result = rs.next();
    prepStmt.close();
    releaseConnection();
    return result;
    Here is what I have in the home interface of the entity bean for this find method:
    public Account findByPrimaryKey(String id)
    throws FinderException, RemoteException;
    In addition here is the entire method in the 'session facade':
    public ArrayList getAccount(String id)
    throws AccountNotFoundException, InvalidParameterException {
    if (id == null)
    throw new InvalidParameterException("null id");
    try {
    account = accountHome.findByPrimaryKey(id);
    } catch (Exception ex) {
    throw new AccountNotFoundException("dag it" + ex.getMessage());
    ArrayList accountList = new ArrayList();
    try {
    AccountDetails accountDetails = account.getDetails();
    accountList.add(accountDetails);
    } catch (RemoteException ex) {
    throw new EJBException("getDetails isn't working in Account ControllerBean: " + ex.getMessage());
    return accountList;
    Thanks again for helping me out.
    James

  • Can't update in mysql

    I am using JSP and MYSQL with a bean that does my database work.
    my search.jsp looks up records, when I click edit it sends the values to my inventory_admin.jsp
    When I make the changes to the data, the data is not saved in the database.
    Please, look see!
    <!--search.jsp-->
    <jsp:useBean id="inventoryBean" scope="session" class="mybeans.inventoryBean" />
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <%// Do search with bean.
         String s = request.getParameter("searchField");
         int searchId = -1;
         if(s != null)
              try
                   searchId = Integer.parseInt(s);
              catch(NumberFormatException e) {}
         //Do actual search with bean
         boolean rc = false;
         if(searchId != -1)
              rc = inventoryBean.findByPrimaryKey(searchId);
              %>
    <form action="search.jsp" method="post" enctype="application/x-www-form-urlencoded">
    <h2 align="center">Software Inventory </h2>
    <p align="center"> </p>
    <p>Lookup:
    <input name="searchField" type="text" id="searchField">
    <input type="submit" name="Submit" value="Submit">
    </p>
    </form>
    <%
         //Output 'not found' message if needed
         if(rc == false)
              out.println("<P><B>Product not found</B></P>");
    %>
    <table width="25%" border="0">
    <tr>
    <td>Item ID:</td>
    <td><jsp:getProperty name="inventoryBean" property="itemid" /></td>
    </tr>
    <tr>
    <td>Product Name:</td>
    <td><jsp:getProperty name="inventoryBean" property="item" /></td>
    </tr>
    <tr>
    <td>Platform:</td>
    <td><jsp:getProperty name="inventoryBean" property="platform" /></td>
    </tr>
    <tr>
    <td>Serial:</td>
    <td><jsp:getProperty name="inventoryBean" property="serial" /></td>
    </tr>
    <tr>
    <td>Description:</td>
    <td><jsp:getProperty name="inventoryBean" property="description" /></td>
    </tr>
    </table>
    <p>&nosave=yes">EDIT</a></p>
    <p align="center"> </p>
    </body>
    </html>
    <!--inventory_admin.jsp-->
    <jsp:useBean id="inventoryBean" scope="session" class="mybeans.inventoryBean" />
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <%-- Copy all form variables at once into the bean--%>
    <jsp:setProperty name="inventoryBean" property="*" />
    <%
         boolean saveResult = false;
         boolean notSaved = false;
         //Save our changes
         String s = request.getParameter("nosave");
         if(s == null || s.equals("yes") == false)
    saveResult = inventoryBean.update();
         else
              notSaved = true;
         //Do search with bean
         s = request.getParameter("itemid");
         int searchId = -1;
         if(s != null)
              try
                   searchId = Integer.parseInt(s);
              catch(NumberFormatException e) {}
         //Do actual search with Bean
         boolean rc;
         if(searchId != -1)
              rc = inventoryBean.findByPrimaryKey(searchId);
    %>
    <h2 align="center">Software Inventory - Edit Mode</h2>
    <FORM action="inventory_admin.jsp" method="post" enctype="application/x-www-form-urlencoded">
    <table width="25%" border="0">
    <tr>
    <td>ITEMID</td>
    <td><jsp:getProperty name="inventoryBean" property="itemid" /></td>
    </tr
    <tr>
    <td>Product Name:</td>
    <td><input name="description" type="text" value="<jsp:getProperty name="inventoryBean" property="item" />"></td>
    </tr>
    <tr>
    <td>Platform:</td>
    <td><input name="description" type="text" value="<jsp:getProperty name="inventoryBean" property="platform" />"></td>
    </tr>
    <tr>
    <td>Serial:</td>
    <td><input name="description" type="text" value="<jsp:getProperty name="inventoryBean" property="serial" />"></td>
    </tr>
    <tr>
    <td>Description:</td>
    <td><input name="description" type="text" value="<jsp:getProperty name="inventoryBean" property="description" />"></td>
    </tr>
    </table>
    <%
         if(notSaved == false)
              if(saveResult == true)
                   out.println("Changes saved");
              else
                   out.println("Changes NOT saved");
    %>
    <p><input type="submit" name="Submit" value="Submit"></p>
    <p align="center"> </p>
    </FORM>
    </body>
    </html>
    //inventory.java
    Here is the Bean Im using:
    // inventoryBean.java - Simple database bean for table products
    package mybeans; // Our custom 'package'.
    import mybeans.DBConfigInfo; // Import helper classes
    import mybeans.DBWorker; // for simpler database programming.
    // Import other packages here.
    import java.sql.*; // For database access.
    import java.util.Hashtable; // For findRecords().
    public class inventoryBean
    private boolean isBeanDataValid = false; // Set when bean contains valid data.
    private boolean isDBError = false; // Stores whether there was a processing error.
    private String dbErrorMsg = "(No error)";
    private DBWorker dbWorker; // Helper object for JDBC programming.
    // Attributes
    private String item = "";
    private String platform = "";
    private String serial = "";
    private String description = "";
    private int itemid = 0; // Primary key field
    public void clear()
    // Clears data in all your properties to 'empty' state.
    item = "";
    platform = "";
    serial = "";
    description = "";
    itemid = 0; // Primary key field
    // Accessor Methods
    public void setItem(String newItem) { item = newItem; }
    public String getItem() { return item; }
    public void setPlatform(String newPlatform) { platform = newPlatform; }
    public String getPlatform() { return platform; }
    public void setSerial(String newSerial) { serial = newSerial; }
    public String getSerial() { return serial; }
    public void setDescription(String newDescription) { description = newDescription; }
    public String getDescription() { return description; }
    public void setItemid(int newItemid) { itemid = newItemid; }
    public int getItemid() { return itemid; }
    // Operations
    // Default constructor.
    public inventoryBean()
    // Create a helper object to work with database.
    // DO NOT DELETE THIS CODE.
    dbWorker = new DBWorker();
    // Database Operations
    // Built-in methods:
    public boolean findByPrimaryKey(int searchId)
    // Use this method to find 1 record by primary key for your table.
    // (After this call, all fields will be loaded into your properties.)
    // Clear existing data, if any.
    clear();
    isBeanDataValid = false;
    // Query by primary key.
    boolean rc = dbWorker.open();
    if(rc == false)
    isDBError = true;
    dbErrorMsg = dbWorker.errorMsg;
    return false;
    try
    // 1) Get a connection.
    Connection conn = dbWorker.getConnection();
    // 2) Create a statement.
    Statement st = conn.createStatement();
    // 3) Build your SQL.
    String sql = "SELECT item, platform, serial, description, " +
    "itemid " +
    "FROM products " +
    "WHERE itemid=" + searchId;
    //System.out.println("DEBUG SQL =" + sql);
    // 4) Get a result set.
    ResultSet rs = st.executeQuery(sql);
    // 5) Move to first record
    if(rs.next())
    // 6) Retrieve fields into your properties using JDBC get??? methods.
    item = rs.getString("item");
    platform = rs.getString("platform");
    serial = rs.getString("serial");
    description = rs.getString("description");
    itemid = rs.getInt("itemid");
    // 7) Ensure non-null String fields with dbWorker.safeStr()
    item = dbWorker.safeStr(item);
    platform = dbWorker.safeStr(platform);
    serial = dbWorker.safeStr(serial);
    description = dbWorker.safeStr(description);
    // Set result code.
    isBeanDataValid = true;
    // 8) Close all DB objects.
    rs.close();
    st.close();
    dbWorker.close(); // Connection too.
    catch(SQLException e)
    System.out.println("Error in findByPrimaryKey (" + e.getMessage() + ")");
    return isBeanDataValid;
    // Update a record
    public boolean update()
    // Use this to update a record by a primary key.
    boolean resultCode = false;
    // Query by primary key.
    boolean rc = dbWorker.open();
    if(rc == false)
    isDBError = true;
    dbErrorMsg = dbWorker.errorMsg;
    return false;
    try // Remember to put all DB code inside a try block!
    // 1) Get a connection.
    Connection conn = dbWorker.getConnection();
    // 2) Create a statement.
    Statement st = conn.createStatement();
    // 3) Build your SQL.
    String sql = "UPDATE products SET item=" + dbWorker.sqlStr(item) + "," +
    "platform=" + dbWorker.sqlStr(platform) + "," +
    "serial=" + dbWorker.sqlStr(serial) + "," +
    "description=" + dbWorker.sqlStr(description)+
    " WHERE itemid=" + itemid;
    //System.out.println("DEBUG SQL =" + sql);
    // 4) Run action query.
    int rowsAffected = st.executeUpdate(sql);
    // 5) See if we succeeded (1 recorded affected).
    if(rowsAffected == 1)
    resultCode = true;
    else
    System.out.println("Warning: Can't update in update()!");
    // 6) Close all DB objects.
    st.close();
    dbWorker.close(); // Connection too.
    catch(SQLException e)
    System.out.println("Error in update (" + e.getMessage() + ")");
    return resultCode;
    // Delete a record
    public boolean delete(int deleteId)
    // Use this to delete a record by a primary key.
    boolean resultCode = false;
    // Query by primary key.
    boolean rc = dbWorker.open();
    if(rc == false)
    isDBError = true;
    dbErrorMsg = dbWorker.errorMsg;
    return false;
    try
    // 1) Get a connection.
    Connection conn = dbWorker.getConnection();
    // 2) Create a statement.
    Statement st = conn.createStatement();
    // 3) Build your SQL.
    String sql = "DELETE FROM products WHERE itemid=" + deleteId;
    //System.out.println("DEBUG SQL =" + sql);
    // 4) Run action query.
    int rowsAffected = st.executeUpdate(sql);
    // 5) See if we succeeded (1 recorded affected).
    if(rowsAffected == 1)
    resultCode = true;
    else
    System.out.println("Warning: Can't delete ID #" + deleteId + " in delete()!");
    // 6) Close all DB objects.
    st.close();
    dbWorker.close(); // Connection too.
    catch(SQLException e)
    System.out.println("Error in delete (" + e.getMessage() + ")");
    return resultCode;
    // Insert a new record.
    public boolean insert(String newItem, String newPlatform, String newSerial, String newDescription,
    int newItemid)
         // Use this to update a record by a primary key.
    boolean resultCode = false;
    // Query by primary key.
    boolean rc = dbWorker.open();
    if(rc == false)
    isDBError = true;
    dbErrorMsg = dbWorker.errorMsg;
    return false;
    try // Remember to put all DB code inside a try block!
    // 1) Get a connection.
    Connection conn = dbWorker.getConnection();
    // 2) Create a statement.
    Statement st = conn.createStatement();
    // 3) Build your SQL.
    String sql="INSERT INTO products(item, platform, serial, description, " +
    "itemid) " +
    "VALUES(" + dbWorker.sqlStr(newItem) + "," + dbWorker.sqlStr(newPlatform) + "," + dbWorker.sqlStr(newSerial) + "," + dbWorker.sqlStr(newDescription) + "," +
    newItemid + ")";
    //System.out.println("DEBUG SQL =" + sql);
    // 4) Run action query.
    int rowsAffected = st.executeUpdate(sql);
    // 5) See if we succeeded (1 recorded affected).
    if(rowsAffected == 1)
    resultCode = true;
    else
    System.out.println("Warning: Can't update in insert()!");
    // 6) Close all DB objects.
    st.close();
    dbWorker.close(); // Connection too.
    catch(SQLException e)
    System.out.println("Error in insert (" + e.getMessage() + ")");
    return resultCode;
    public int findMaxPrimaryKey()
    // Use this method to find the current max. value for a primary key
    // in the database for a given table.
    int retVal = -1;
    // Query by primary key.
    boolean rc = dbWorker.open();
    if(rc == false)
    isDBError = true;
    dbErrorMsg = dbWorker.errorMsg;
    return -1;
    try // Remember to put all DB code inside a try block!
    // 1) Get a connection.
    Connection conn = dbWorker.getConnection();
    // 2) Create a statement.
    Statement st = conn.createStatement();
    // 3) Build your SQL.
    String sql = "SELECT MAX(itemid) FROM products";
    //System.out.println("DEBUG SQL =" + sql);
    // 4) Get a result set.
    ResultSet rs = st.executeQuery(sql);
    // 5) Move to first record
    if(rs.next())
    // 6) Retrieve fields into your properties using JDBC get??? methods.
    retVal = rs.getInt(1); // Get first and only column.
    // 7) Close all DB objects.
    rs.close();
    st.close();
    dbWorker.close(); // Connection too.
    catch(SQLException e)
    System.out.println("Error in findMaxPrimaryKey (" + e.getMessage() + ")");
    return retVal;
    public Hashtable findRecords(String filter, String orderBy)
    // Use this method to return a Hashtable filled with
    // one or more records. You can specified a 'filter'
    // for finding records and 'orderBy' will determine the sort order.
    Hashtable retVal = new Hashtable();
    retVal.put("ROWCOUNT", "0");
    retVal.put("COLUMNCOUNT", "0");
    retVal.put("STATUS", "EMPTY");
    // Query by primary key.
    boolean rc = dbWorker.open();
    if(rc == false)
    isDBError = true;
    dbErrorMsg = dbWorker.errorMsg;
    return retVal;
    try // Remember to put all DB code inside a try block!
    // 1) Get a connection.
    Connection conn = dbWorker.getConnection();
    // 2) Create a statement.
    Statement st = conn.createStatement();
    // 3) Build your SQL.
    String sql = "SELECT item, platform, serial, description, " +
    "itemid " +
    "FROM products " +
    "WHERE " + filter + " " +
    "ORDER BY " + orderBy;
    //System.out.println("DEBUG SQL =" + sql);
    // 4) Get a result set.
    ResultSet rs = st.executeQuery(sql);
    int rowCount = 0;
    // 5) Move to first record (and then next) record.
    while(rs.next())
    // 6) Retrieve fields into your properties using JDBC get??? methods.
    String thisItem = rs.getString("item");
    String thisPlatform = rs.getString("platform");
    String thisSerial = rs.getString("serial");
    String thisDescription = rs.getString("description");
    int thisItemid = rs.getInt("itemid");
    // 7) Ensure non-null String fields with dbWorker.safeStr()
    thisItem = dbWorker.safeStr(thisItem);
    thisPlatform = dbWorker.safeStr(thisPlatform);
    thisSerial = dbWorker.safeStr(thisSerial);
    thisDescription = dbWorker.safeStr(thisDescription);
    // 8) Load this row into our Hashtable.
    // The convention here is to pack each row's column name with an ID
    // indicating the row. "ProjectId" + "0" = "ProjectId0" ===mapped to===> Value
    // Put this record into Hashtable.
    retVal.put("item" + rowCount, thisItem);
    retVal.put("platform" + rowCount, thisPlatform);
    retVal.put("serial" + rowCount, thisSerial);
    retVal.put("description" + rowCount, thisDescription);
    retVal.put("itemid" + rowCount, "" + thisItemid);
    rowCount++;
    // 9) Close all DB objects.
    rs.close();
    st.close();
    dbWorker.close(); // Connection too.
    // Write info to our hashtable--Since this container hold virtually anything,
    // you can put in whatever 'metadata' you want about your result set.
    retVal.put("ROWCOUNT", "" + rowCount);
    retVal.put("COLUMNCOUNT", "5");
    retVal.put("STATUS", "OK");
    catch(SQLException e)
    System.out.println("Error in findRecords (" + e.getMessage() + ")");
    retVal.put("STATUS", "ERROR");
    return retVal;
    //============================================================
    // DO NOT CHANGE THE CODE BELOW.
    //============================================================
    public boolean isValid()
    // Does bean contain real data?
    return isBeanDataValid;
    public boolean isError()
    // Returns true if there was a DB error.
    return isDBError;
    public String getErrorMsg()
    // Returns error message, if any.
    return dbErrorMsg;
    //=====================================================================
    // TODO: Remember to comment out main() with /* */ for production code!
    //=====================================================================
    // TEST DRIVER CODE
    public static void main(String[] args)
    // Test driver code goes here.
    String beanName = "inventoryBean";
    String tableName = "products";
    boolean isDataValidationError = false;
    // Exercise CRUD functionality of this bean.
    System.out.println("==============================================================");
    System.out.println("Starting Test Driver for bean " + beanName + "....");
    System.out.println("==============================================================");
    // Create bean.
    inventoryBean myBean = new inventoryBean();
    // Create a new record.
    int newId = myBean.findMaxPrimaryKey();
    newId++;
    boolean rc = myBean.insert("e", "t", "g", "R",
    newId);
    if(rc)
    System.out.println("SUCCESS: Inserted new record #= " + newId + ".");
    else
    System.out.println("ERROR! Can't insert record #= " + newId + ".");
    System.out.println("====================================================");
    System.out.println("VALIDATION FAILED: Test driver generated an error.");
    System.out.println("====================================================");
    return;
    // Retrieve a record
    rc = myBean.findByPrimaryKey(newId);
    if(rc)
    System.out.println("SUCCESS: Record #" + newId + " found.");
    else
    System.out.println("====================================================");
    System.out.println("VALIDATION FAILED: Test driver generated an error.");
    System.out.println("====================================================");
    System.out.println("ERROR! Record #" + newId + " NOT found.");
    // Simulate using set??? accessor methods with test data.
    // (Note: We don't change the primary key.)
    int testItemid = newId;
    System.out.println("Testing set???() accessor methods....");
    System.out.println("Setting Record #" + newId + " to:");
    System.out.println(" inventoryBean.setItem(testItem); // = R");
    myBean.setItem(testItem);
    System.out.println(" inventoryBean.setPlatform(testPlatform); // = Y");
    myBean.setPlatform(testPlatform);
    System.out.println(" inventoryBean.setSerial(testSerial); // = E");
    myBean.setSerial(testSerial);
    System.out.println(" inventoryBean.setDescription(testDescription); // = k");
    myBean.setDescription(testDescription);
    System.out.println(" inventoryBean.setItemid(testItemid); // = " + newId);
    myBean.setItemid(testItemid);
    // Call update.
    rc = myBean.update();
    if(rc)
    System.out.println("SUCCESS: Record #" + newId + " updated.");
    else
    System.out.println("ERROR! Record #" + newId + " NOT updated.");
    System.out.println("====================================================");
    System.out.println("VALIDATION FAILED: Test driver generated an error.");
    System.out.println("====================================================");
    return;
    // Requery and validate each field.
    rc = myBean.findByPrimaryKey(newId);
    if(rc)
    System.out.println("SUCCESS: Updated Record #" + newId + " found.");
    else
    System.out.println("====================================================");
    System.out.println("VALIDATION FAILED: Test driver generated an error.");
    System.out.println("====================================================");
    System.out.println("ERROR! Record #" + newId + " NOT found");
    // Simulate using get??? accessor methods.
    // Validate updated values against test values.
    System.out.println("Validating Record #" + newId + ":");
    String testData;
    String actualItem = myBean.getItem();
    testData = "R";
    if(testData.equals(actualItem))
    System.out.println(" OK: inventoryBean.getItem() = actualItem");
    else
    System.out.println(" ERROR! inventoryBean.getItem() returned [" + actualItem + "] instead of [R]");
    isDataValidationError = true;
    String actualPlatform = myBean.getPlatform();
    testData = "Y";
    if(testData.equals(actualPlatform))
    System.out.println(" OK: inventoryBean.getPlatform() = actualPlatform");
    else
    System.out.println(" ERROR! inventoryBean.getPlatform() returned [" + actualPlatform + "] instead of [Y]");
    isDataValidationError = true;
    String actualSerial = myBean.getSerial();
    testData = "E";
    if(testData.equals(actualSerial))
    System.out.println(" OK: inventoryBean.getSerial() = actualSerial");
    else
    System.out.println(" ERROR! inventoryBean.getSerial() returned [" + actualSerial + "] instead of [E]");
    isDataValidationError = true;
    String actualDescription = myBean.getDescription();
    testData = "k";
    if(testData.equals(actualDescription))
    System.out.println(" OK: inventoryBean.getDescription() = actualDescription");
    else
    System.out.println(" ERROR! inventoryBean.getDescription() returned [" + actualDescription + "] instead of [k]");
    isDataValidationError = true;
    int actualItemid = myBean.getItemid();
    if(actualItemid == newId)
    System.out.println(" OK: inventoryBean.getItemid() = actualItemid");
    else
    System.out.println(" ERROR! inventoryBean.getItemid() returned [" + actualItemid + "] instead of [" + newId + "]");
    isDataValidationError = true;
    // Cleanup with delete.
    rc = myBean.delete(newId);
    if(rc)
    System.out.println("SUCCESS: Record #" + newId + " deleted.");
    else
    System.out.println("ERROR! Record #" + newId + " NOT deleted.");
    // Now test out findRecords() for up to 100 records.
    Hashtable data = myBean.findRecords("itemid > 0", "itemid");
    String s = (String)data.get("STATUS");
    if(s != null && s.equals("OK"))
    s = (String)data.get("ROWCOUNT");
    int rowCount = Integer.parseInt(s);
    if(rowCount > 100) // Just output first 100 records.
    rowCount = 100;
    System.out.println("SUCCESS: Returning " + rowCount + " records (100 max.) using findRecords():");
    for(int i = 0; i < rowCount; i++)
    System.out.println(" Row #" + i + "=" +
    data.get("item" + i) + ", " +
    data.get("platform" + i) + ", " +
    data.get("serial" + i) + ", " +
    data.get("description" + i) + ", " +
    data.get("itemid" + i));
    else
    System.out.println("ERROR! No rows returned using findRecords()!");
    System.out.println("====================================================");
    System.out.println("VALIDATION FAILED: Test driver generated an error.");
    System.out.println("====================================================");
    return;
    if(isDataValidationError == false)
    // Print final success message.
    System.out.println("================================================================================");
    System.out.println("VALIDATION SUCCESS! Bean " + beanName + " passed all automated tests.");
    System.out.println("================================================================================");
    else
    System.out.println("====================================================================================");
    System.out.println("ERROR! Tests completed but bean " + beanName + " had a data validation error.");
    System.out.println("====================================================================================");

    Couple of pointers.
    1 - use [ code ] tags to post code
    2 - that is WAY too much code for more than a cursory glance. You're lucky the problem was easy to spot.
    Your problem lies in your edit JSP form:
    <td>Product Name:</td>
    <td><input name="description" type="text" value="<jsp:getProperty name="inventoryBean" property="item" />"></td>Note that the name of the input field is different from the jsp property you are populating it with.
    In fact, all of your input fields have a name of "description"
    I would recommend on your inventory_admin.jsp page that you put the following debugging code to make sure that the parameter values come through and are set correctly.
      out.println("name = param: " + request.getParameter("name") + "bean = " + inventoryBean.getName() + "<BR>");
      out.println("description = param:" + request.getParameter("description") + "bean = " + inventoryBean.getDescription() + "<BR>");
      ...

  • Cannot deploy EntityBean from Weblogic 5.1

    Hi everyone,
    I'm relatively new to EJB deployment, but there is an Entity bean that I was able to deploy using Weblogic 4.0 and fail to do the same with Weblogic 5.1, although I'm going through all the necessary steps, like creating xmls (ejb_jar, weblogic-cmp-rdbms-jar, and weblogic-ejb-jar), creating a jar file, and recompiling it using weblogic.ejbc, and that's where it stops. While it works fine with session beans, every time I'm trying to deploy entity bean, it gives me the following message:
    ERROR: Error from ejbc: [9.1.5.1] In EJB EmployerEntityEJB, there is an ejbPostCreate method ejbPostCreate() that has no matching ejbCreate method.
    Yet my ejbCreate and ejbPostCreate methods do match, unless I'm missing something, but at this point I have no idea what exactly. Any kind of help would be great, 'cause I'm almost out of ideas.
    Here's the code I'm working on:
    EmployerEntity.java:
    import java.rmi.*;
    import java.sql.*;
    import javax.ejb.*;
    import java.util.*;
    public interface EmployerEntity extends EJBObject, Remote {
    public boolean postingUpdate(Hashtable posting) throws RemoteException,SQLException;
    public void callingBreakHashtable(Hashtable posting) throws RemoteException;
    EmployerEntityHome.java:
    import java.rmi.*;
    import javax.ejb.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    public interface EmployerEntityHome extends EJBHome{
    public EmployerEntity create(Hashtable posting) throws RemoteException, EJBException, CreateException;
    public EmployerEntity findByPrimaryKey(EmployerEntityPK job_id) throws FinderException,RemoteException;
    public EmployerEntity findByPosition(int job_id) throws FinderException,RemoteException;
    EmployerEntityPK.java:
    import java.io.Serializable;
    public class EmployerEntityPK {
    public int job_id;
    and finally EmployerEntityBean.java (I left only ejbCreat and ejbPostCreate methods, so that I won't confuse anybody):
    import java.io.*;
    import java.util.*;
    import javax.ejb.*;
    import javax.naming.*;
    import java.rmi.*;
    import java.sql.*;
    //and local classes
    public class EmployerEntityBean extends LocalClassEntityBean {
    Hashtable posting=new Hashtable();
    public EmployerEntityBean() {}
    public EmployerEntityPK ejbCreate(Hashtable posting) throws EJBException, CreateException {
    if (posting_entity_flag)
    this.posting=posting;
    callingBreakHashtable(posting);
    Syslog.debug(this,"EJBCreate Called ");
    return null;
    public void ejbPostCreate(Hashtable posting) throws EJBException {
    Syslog.debug(this,"EJBPostCreate Called ");
    Thanks for your help.
    PS. Also, could it be that the error that I'm getting might be caused by something other than simply mismatching ejbCreate and ejbPostCreate? If so, what are the other possible reasons?
    Thanks

    Hi,
    First of all, you don't need to add EJBException in your method definition as its a runtime exception. Next your ejbPostCreate() is missing the CreateException and thats the reason you have a mismatch.
    Also your remote interface should extend EJBObject ( which is a subclass of java.rmi.Remote). Catch the SQLException and rethrow it as an EJBException with proper message. And finally I take it that LocalClassEntityBean implements EntityBean.
    Best wishes

  • Error while deploying CMP.. can u pls tell me...

    Hi,
    Below is the error my jboss 3.2.3 container is throwing when i tried to deploy my CMP entity bean. It says
    my ejbFindByPrimaryKey() method must be implemented,but in a CMP i am told the container will take care of the implementation, one just has to specify it in the home object.. can anyone pls tell me where i could have gone wrong.
    2004-07-09 12:47:39,825 INFO [org.jboss.deployment.MainDeployer] Starting deployment of package: file:/D:/jboss-3.2.3/server/default/deploy/product.jar
    2004-07-09 12:47:40,404 WARN [org.jboss.ejb.EJBDeployer.verifier] EJB spec violation:
    Bean : Product
    Section: 12.2.2
    Warning: The class must be defined as public and must not be abstract.
    2004-07-09 12:47:40,404 WARN [org.jboss.ejb.EJBDeployer.verifier] EJB spec violation:
    Bean : Product
    Section: 12.2.5
    Warning: Every entity bean must define the ejbFindByPrimaryKey method.
    2004-07-09 12:47:40,419 ERROR [org.jboss.deployment.MainDeployer] could not create deployment: file:/D:/jboss-3.2.3/server/default/deploy/product.jar
    org.jboss.deployment.DeploymentException: Verification of Enterprise Beans failed, see above for error messages.
         at org.jboss.ejb.EJBDeployer.create(EJBDeployer.java:491)
         at org.jboss.deployment.MainDeployer.create(MainDeployer.java:786)
         at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:641)
         at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:605)
         at sun.reflect.GeneratedMethodAccessor20.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at org.jboss.mx.capability.ReflectedMBeanDispatcher.invoke(ReflectedMBeanDispatcher.java:284)
         at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:546)
         at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:177)
         at $Proxy6.deploy(Unknown Source)
         at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:302)
         at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:476)
         at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:201)
         at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.loop(AbstractDeploymentScanner.java:212)
         at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.run(AbstractDeploymentScanner.java:191)

    This is my code
    ProductBean
    import javax.ejb.EntityContext;
    import javax.ejb.EntityBean;
    public abstract class ProductBean implements EntityBean {
         protected EntityContext ctx;
         //All set and get Methods
         public abstract String getName();
         public abstract void setName(String name);
         public abstract String getDescription() ;
         public abstract void setDescription(String desc);
         public abstract double getBasePrice() ;
         public abstract void setBasePrice(double baseprice);
         public abstract String getProductID();     
         public abstract void setProductID(String prodname);
         //EJB required Methods
         public void ejbActivate(){
              System.out.println("ejbActivate called");
         public void ejbRemove(){
              System.out.println("ejbRemove called");
         public void ejbPassivate(){
              System.out.println("ejbPassivate called");
         public void ejbLoad(){
              System.out.println("ejbLoad called");
         public void ejbStore(){
              System.out.println("ejbStore called");
         public void setEntityContext(EntityContext ctx){
              System.out.println("setEntityContext called");
              this.ctx=ctx;
         public void UnsetEntityContext(){
              System.out.println("UnsetEntityContext called");
              this.ctx=null;
         public void ejbPostCreate(String productID,String name,String description,double basePrice){
              System.out.println("ejbPostCreate called");
         public ProductKey ejbCreate(String productID,String name,String description,double basePrice){
              System.out.println("Create method  called");
              setProductID(productID);
              setName(name);
              setDescription(description);
              setBasePrice(basePrice);
              return new ProductKey(productID); // i am not sure which to retun,
              //return null;
                                               //Well just on a note for the above
                                              // I READ THAT CMP2.0 MUST RETURN NULL, BUT IN ED-ROMANS MASTERING
                                              // EJB  IT SAYS THE BEAN MUST RETURN THE PRIMARY KEY CLASS.
                                              // I HAVE TRIED BOTH THE ABOVE RETURN VALUES, STILL I GET THE SAME
                                              / /ERROR.
    HomeInterface
    import java.rmi.RemoteException;
    import java.util.Collection;
    import javax.ejb.CreateException;
    import javax.ejb.EJBHome;
    import javax.ejb.FinderException;
    public interface ProductHome extends EJBHome {
         public Product create(String productID,String name,String description,double basePrice)throws CreateException,RemoteException;
         public Product findByPrimaryKey(ProductKey key) throws FinderException,RemoteException;
         public Collection findByName(String name) throws RemoteException,FinderException;
         public Collection findByDescription(String desc) throws RemoteException,FinderException;
         public Collection findByBasePrice(double basePrice) throws RemoteException,FinderException;
         public Collection findByExpensiveProduct(double minPrice ) throws RemoteException,FinderException;
         public Collection findCheapProducts(double maxPrice) throws RemoteException,FinderException;
         public Collection findAllProducts() throws RemoteException,FinderException;
    RemoteInterface
    import java.rmi.RemoteException;
    import javax.ejb.EJBObject;
    public interface Product extends EJBObject {
         public String getName() throws RemoteException;
         public void setName(String name)throws RemoteException;
         public String getDescription() throws RemoteException;
         public void setDescription(String desc) throws RemoteException;
         public double getBasePrice() throws RemoteException;
         public void setBasePrice(double baseprice)throws RemoteException;
         public String getProductID()throws RemoteException;     
    ProductKey class - This is my PRIMARY KEY CLASS
    import java.io.Serializable;
    public class ProductKey implements Serializable{
         public String productID;
         public ProductKey(){          
         public ProductKey(String prodID){
              productID=prodID;
         public String toString(){
              return productID;
         public int hashCode()     {
              return productID.hashCode();
         public boolean equals(Object prod){
              return ((ProductKey)prod).productID.equals(productID);
    This is my ejb-jar.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
    <ejb-jar >
       <description><![CDATA[No Description.]]></description>
       <display-name>Generated by XDoclet</display-name>
       <enterprise-beans>
          <entity>
             <description><![CDATA[]]></description>
             <ejb-name>Product</ejb-name>
             <home>ProductHome</home>
             <local-home>ProductHomeLocal</local-home>
             <remote>Product</remote>
             <local-remote>ProductLocal</local-remote>
             <ejb-class>ProductBean</ejb-class>
               <persistence-type>Bean</persistence-type>
               <prim-key-class>ProductKey</prim-key-class>
               <reentrant>False</reentrant>     
               <cmp-version>2.x</cmp-version>
              <abstract-schema-name>ProductBean</abstract-schema-name>
              <cmp-field> <field-name>productID</field-name></cmp-field>
              <cmp-field> <field-name>name</field-name></cmp-field>
              <cmp-field> <field-name>description</field-name></cmp-field>
              <cmp-field> <field-name>basePrice</field-name></cmp-field>       
               <primkey-field>productID</primkey-field>
            <query>
                 <query-method>
                      <method-name>findByName</method-name>
                           <method-params>
                                <method-param>java.lang.String</method-param>
                           </method-params>
                 </query-method>
                 <ejb-ql>
                           <![CDATA[SELECT OBJECT(a) from ProductBean as a where name=?1]]>
                 </ejb-ql>
            </query>
            <query>
                 <query-method>
                      <method-name>findByBasePrice</method-name>
                           <method-params>
                                <method-param>double</method-param>
                           </method-params>
                 </query-method>
                 <ejb-ql>
                           <![CDATA[SELECT OBJECT(a) from ProductBean as a where basePrice = ?1]]>
                 </ejb-ql>
            </query>
            <query>
                 <query-method>
                      <method-name>findExpensiveProducts</method-name>
                           <method-params>
                                <method-param>double</method-param>
                           </method-params>
                 </query-method>
                 <ejb-ql>
                           <![CDATA[SELECT OBJECT(a) from ProductBean as a where basePrice > ?1]]>
                 </ejb-ql>
            </query>
            <query>
                 <query-method>
                      <method-name>findCheapProducts</method-name>
                           <method-params>
                                <method-param>double</method-param>
                           </method-params>
                 </query-method>
                 <ejb-ql>
                           <![CDATA[SELECT OBJECT(a) from ProductBean as a where basePrice < ?1]]>
                 </ejb-ql>
            </query>
                    <query>
                 <query-method>
                      <method-name>findAllProducts</method-name>
                           <method-params>
                                <method-param>double</method-param>
                           </method-params>
                 </query-method>
                 <ejb-ql>
                           <![CDATA[SELECT OBJECT(a) from ProductBean as a where productID IS NOT NULL]]>
                 </ejb-ql>
            </query>
                 </entity>
          </enterprise-beans>
       </ejb-jar>
    This is my jboss.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.0//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_0.dtd">
    <jboss>
       <unauthenticated-principal>nobody</unauthenticated-principal>
       <enterprise-beans>
          <entity>
             <ejb-name>Product</ejb-name>
             <jndi-name>ProductHome</jndi-name>
              <local-jndi-name>ProductHomeLocal</local-jndi-name>
          </entity>
       </enterprise-beans>
       <resource-managers>
       </resource-managers>
    </jboss>
    This is my jbosscmp-jdbc.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE jbosscmp-jdbc PUBLIC "-//JBoss//DTD JBOSSCMP-JDBC 3.0//EN" "http://www.jboss.org/j2ee/dtd/jbosscmp-jdbc_3_0.dtd">
    <jbosscmp-jdbc>
       <defaults>
         <datasource>java:/OracleDS</datasource>
         <datasource-mapping>Oracle8</datasource-mapping>
       </defaults>
       <enterprise-beans>
          <entity>
             <ejb-name>Product</ejb-name>
             <table-name>ProductTable</table-name>
             <cmp-field>
                <field-name>productID</field-name>
                <column-name>PRODUCTID</column-name>
            </cmp-field>
             <cmp-field>
                <field-name>name</field-name>
                <column-name>NAME</column-name>
            </cmp-field>
            <cmp-field>
                <field-name>description</field-name>
                <column-name>DESCRIPTION</column-name>
            </cmp-field>
            <cmp-field>
                <field-name>basePrice</field-name>
                <column-name>BASEPRICE</column-name>
            </cmp-field>
          </entity>
       </enterprise-beans>
    </jbosscmp-jdbc>

  • Composite Primary Key Error

    I am using Sun One App Server PE8.
    I have a class with a composite primary key field. When I place the following method in my Home interface:
    public MyEjb findByPrimaryKey(MyEjbPrimaryKey pk) throws FinderException, RemoteException;I get the following error when deploying:
    ejbFindByPrimaryKey(EjbPrimaryKey) is already defined in MyEjb1368202910_ConcreteImpl
        public MyEjbPrimaryKey ejbFindByPrimaryKey (MyEjbPrimaryKey key)However, If i remove this method from the Home interface, i get the following error when running the verification tool:
    Error: No single arg findByPrimaryKey(PrimaryKeyClass) method was found in home interface class [ MyEjb ].However, I can still deploy the EAR successfully.
    Another related symptom of this problem, is if I include the following method in my Home interface:
    public MyEjb findByPrimaryKey(String pkField1, String pkField2) throws FinderException, RemoteException;And call this method, I get the following exception at runtime:
    java.rmi.RemoteException: Bean class for ejb [MyEjb] does not define a method corresponding to [Home] interface method [public abstract MyEjb MyEjbHome.findByPrimaryKey(java.lang.String,java
    .lang.String) throws javax.ejb.FinderException,java.rmi.RemoteException]I get these same problems with all EJB's that use composite keys. Has anyone else had this problem?
    Thanks
    toby

    This is a CMP bean, with no ejbFindByPrimaryKey in the Bean class. Below, i have included the Home interface and the Bean class (with unneccessary code removed)
    Thanks for looking at this for me.
    BEAN CLASS
    package lands.mc.bus.prod;
    import java.rmi.*;
    import java.util.*;
    import javax.ejb.*;
    public abstract class TopoMapBean implements EntityBean
      private EntityContext entity;
      public TopoMapBean()
      public void setEntityContext(EntityContext ctx)
        entity = ctx;
      public void unsetEntityContext()
        entity = null;
      public TopoMapPrimaryKey ejbCreate(String mapName, String mapNumber, String mnemonic,String edition, String scale)
      throws CreateException
        // call setters...
        return null;
      public void ejbPostCreate( String mapName,
                                                   String mapNumber,
                                             String mnemonic,
                                             String edition,
                                             String scale )
      removed set/get methods
      public void ejbStore() {}
      public void ejbLoad() {}
      public void ejbActivate() {}
      public void ejbPassivate() {}
      public void ejbRemove() {}
    }HOME INTERFACE
    package lands.mc.bus.prod;
    import java.rmi.*;
    import java.util.*;
    import javax.ejb.*;
    public interface TopoMapHome extends EJBHome
      public TopoMap create(String mapName,
                            String mapNumber,
                            String mnemonic,
                            String edition,
                            String scale
      throws CreateException, RemoteException;
      public TopoMap findByPrimaryKey(String mapNumber, String edition) throws FinderException, RemoteException;
    // doesnt deploy with this signature
    //  public TopoMap findByPrimaryKey(TopoMapPrimaryKey pkey) throws FinderException;
    // have to use this method instead of findByPrimaryKey(String, String) above
      public TopoMap findTopoMap(String mapNumber, String edition) throws FinderException, RemoteException;

  • Error when deploying an CMP-Entity EJB

    Hi ,
    I am unable to deploy a simple example of CMP ,when i select Entity,then select Deployment Settings->Generate Default SQL,
    My SQL Query is:'SELECT OBJECT(p) FROM Product p' for FfindAllProducts().
    I get the error message:
    ERROR:while generating SQL.
    The SELECT clause has a return type that does not match the return type
    of the select query for which it is defined
    EJB QL statement: 'SELECT OBJECT(p)fROM Product p'
    EJB QL method:public abstract java.util.Collection com.aa.ProductHome.findAllProducts() throws javax.ejb.FinderException,java.rmi.RemoteException.
    Followinng are the codes of My bean
    ProductHome.java
    import javax.ejb.*;
    import java.rmi.RemoteException;
    import java.util.Collection;
    public interface ProductHome extends EJBHome
    Product create(String productId,String name , String description , double basePrice) throws CreateException,RemoteException;
    public Product findByPrimaryKey(ProductPK key) throws FinderException,RemoteException;
    public Collection findByName(String name) throws FinderException,RemoteException;
    public Collection findByDescription(String description) throws FinderException,RemoteException;
    public Collection findAllProducts() throws FinderException,RemoteException;
    ProductBean.java
    import javax.ejb.*;
    import java.rmi.RemoteException;
    public class ProductBean implements EntityBean
    protected EntityContext ctx;
    public String productid;
    public String name;
    public String description;
    public ProductBean()
    public String getName() throws RemoteException
    return this.name;
    public void setName(String name) throws RemoteException
    this.name=name;
    public String getDescription() throws RemoteException
    return this.description;
    public void setDescription(String description) throws RemoteException
    this.description=description;
    public String getProductId() throws RemoteException
    return this.productid;
    public void setProductId(String ProductId) throws RemoteException
    this.productid=ProductId;
    public void ejbActivate()
    public void ejbPassivate()
    public void ejbRemove()
    public void ejbLoad()
    public void ejbStore()
    public void setEntityContext(EntityContext ctx)
    this.ctx = ctx;
    public void unsetEntityContext()
    this.ctx = null;
    public void ejbPostCreate(String productId,String name,String description,double baseprice)
    public ProductPK ejbCreate(String productId,String name,String description,double baseprice) throws CreateException,RemoteException
    called ");
    setName(name);
    setProductId(productId);
    setDescription(description);
    return null;
    Product.java
    import javax.ejb.*;
    import java.rmi.RemoteException;
    public interface Product extends EJBObject
    public String getName() throws RemoteException;
    public void setName(String name) throws RemoteException;
    public String getDescription() throws RemoteException;
    public void setDescription(String description) throws RemoteException;
    public String getProductId() throws RemoteException;
    public void setProductId(String productid) throws RemoteException;
    ProductClient.java
    import java.rmi.*;
    import javax.rmi.*;
    import javax.naming.*;
    import javax.ejb.*;
    import java.util.*;
    public class ProductClient
    public static void main(String ars[])
    ProductHome home=null;
    try
    Context initial = new InitialContext();
    Context myEnv = (Context)initial.lookup("java:comp/env");
    Object objref = myEnv.lookup("ejb/TheProduct");
    home = (ProductHome)PortableRemoteObject.narrow(objref,ProductHome.class);
    home.create("123-446-7890","p5-350","350 Mhz Pentium",200 );
    home.create("123-446-7891","p5-400","400 Mhz Pentium",300 );
    home.create("123-446-7892","p5-450","450 Mhz Pentium",400 );
    home.create("123-446-7893","p5-500","500 Mhz Pentium",500 );
    home.create("123-446-7894","p5-550","550 Mhz Pentium",600 );
    Iterator i = home.findByName("p5-400").iterator();
    System.out.println(" Product Match the name of p5-400 " );
    if ( i.hasNext() )
    Product prod = (Product)PortableRemoteObject.narrow(i.next(),Product.class);
    System.out.println(prod.getDescription());
    else
    throw new Exception(" Could not find Product ");
    catch(Exception e)
    System.out.println("Caught Exception " );
    e.printStackTrace();
    finally
    if ( home != null)
    System.out.println(" Destroying all products " );
    try
    Iterator i = home.findAllProducts().iterator();
    while ( i.hasNext() )
    Product prod = (Product)PortableRemoteObject.narrow(i.next(),Product.class);
    if (prod.getProductId().startsWith("123"))
    prod.remove();
    catch (Exception e)
    e.printStackTrace();
    ProductPk.java
    import java.io.Serializable;
    public class ProductPK implements java.io.Serializable
    public String ProductId ;
    public ProductPK(String id)
    this.ProductId = id;
    public ProductPK()
    public String toString()
    return ProductId;
    public int hashCode()
    return ProductId.hashCode();
    public boolean equals(Object Product)
    return ((ProductPK)Product).ProductId.equals(ProductId);

    can u pls tell me u are using ejb1.1 specifications or ejb2.0 specifications.in both cases pls shoe u are descripters so that i can check.

  • What is the problem?

    I want to deploy a CMP Entity Bean in weblogic6.1SP2,but I meet an error,what should I do to solve the problem?
    the error code:
    <2003-4-7 ~{OBNg~}02~{J1~}27~{7V~}24~{Ck~}> <Error> <J2EE> <Error deploying application SVC:
    Unable to deploy EJB: CMPSvc from SVC.jar:
    The Container-Managed Persistence Entity EJB failed while creating its SQL Type
    Map. The error was:
    Io ~{Rl3#~}: Connection reset by peer: socket write error
    and my original code:
    SVC.java(remote interface)
    package CMPEntityBean;
    import javax.ejb.*;
    import java.rmi.RemoteException;
    public interface SVC extends EJBObject
         public java.lang.String getSvcID() throws RemoteException;
         public java.lang.String getSvcName() throws RemoteException;
         public void setSvcID(java.lang.String svcID) throws RemoteException;
         public void setSvcName(java.lang.String svcName) throws RemoteException;
    SVCHome.java (home interface file)
    package CMPEntityBean;
    import javax.ejb.*;
    import java.rmi.RemoteException;
    import java.util.Collection;
    public interface SVCHome extends EJBHome
    public SVC create(java.lang.String svcID,java.lang.String svcName) throws CreateException,RemoteException;
    public SVC findByPrimaryKey(CMPEntityBean.SVCPK key) throws FinderException,RemoteException;
    public Collection findBySvcName(java.lang.String svcName) throws FinderException,RemoteException;
    SVCBean.java (Enterprise Bean file)
    package CMPEntityBean;
    import javax.ejb.*;
    public abstract class SVCBean implements EntityBean
         protected EntityContext ctx;
         public abstract java.lang.String getSvcID();
         public abstract java.lang.String getSvcName();
         public abstract void setSvcID(java.lang.String svcID);
         public abstract void setSvcName(java.lang.String svcName);
         public void ejbActivate(){}
         public void ejbRemove(){}
         public void ejbPassivate(){}
         public void ejbLoad(){}
         public void ejbStore(){}
         public void setEntityContext(EntityContext ctx)
         this.ctx = ctx;
         public void unsetEntityContext()
         this.ctx = null;
         public void ejbPostCreate(String svcID,String svcName){}
         public SVCPK ejbCreate(String svcID,String svcName)
         setSvcID(svcID);
         setSvcName(svcName);
         return new SVCPK(svcID);
    ejb-jar.xml
    <?xml version="1.0"?>
    <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
    <ejb-jar>
    <enterprise-beans>
    <entity>
    <ejb-name>CMPSvc</ejb-name>
    <home>CMPEntityBean.SVCHome</home>
    <remote>CMPEntityBean.SVC</remote>
    <ejb-class>CMPEntityBean.SVCBean</ejb-class>
    <persistence-type>Container</persistence-type>
    <prim-key-class>CMPEntityBean.SVCPK</prim-key-class>
    <reentrant>False</reentrant>
    <cmp-version>2.x</cmp-version>
    <abstract-schema-name>SVCBean</abstract-schema-name>
    <cmp-field>
    <field-name>svcID</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>svcName</field-name>
    </cmp-field>
    <!--prim-key-class>svcID</prim-key-class-->
    <query>
    <query-method>
    <method-name>findBySvcName</method-name>
    <method-params>
    <method-param>java.lang.String</method-param>
    </method-params>
    </query-method>
         <!--result-type-mapping>Local</result-type-mapping-->
    <ejb-ql>
    SELECT OBJECT(a) FROM SVCBean a WHERE svcName = ?1
    </ejb-ql>
    </query>
    </entity>
    </enterprise-beans>
    <assembly-descriptor>
    <container-transaction>
    <method>
    <ejb-name>CMPSvc</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>*</method-name>
    </method>
    <trans-attribute>Required</trans-attribute>
    </container-transaction>
    </assembly-descriptor>
    </ejb-jar>
    weblogic-ejb-jar.xml
    <?xml version="1.0"?>
    <!DOCTYPE weblogic-ejb-jar PUBLIC "-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN" "http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd" >
    <weblogic-ejb-jar>
    <weblogic-enterprise-bean>
    <ejb-name>CMPSvc</ejb-name>
    <entity-descriptor>
    <entity-cache>
         <max-beans-in-cache>1000</max-beans-in-cache>
    </entity-cache>
    <persistence>
         <persistence-type>
         <type-identifier>WebLogic_CMP_RDBMS</type-identifier>
         <type-version>6.0</type-version>
         <type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
         </persistence-type>
         <persistence-use>
         <type-identifier>WebLogic_CMP_RDBMS</type-identifier>
         <type-version>6.0</type-version>
         </persistence-use>
    </persistence>
    </entity-descriptor>
    <jndi-name>cmpsvc</jndi-name>
    </weblogic-enterprise-bean>
    </weblogic-ejb-jar>
    weblogic-cmp-rdbms-jar.xml
    <!DOCTYPE weblogic-rdbms-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB RDBMS Persistence//EN' 'http://www.bea.com/servers/wls600/dtd/weblogic-rdbms-persistence.dtd'>
    <weblogic-rdbms-jar>
    <weblogic-rdbms-bean>
    <ejb-name>CMPSvc</ejb-name>
    <data-source-name>ucisOra</data-source-name>
    <table-name>TAB_SVC</table-name>
    <field-map>
    <cmp-field>svcName</cmp-field>
    <dbms-column>svcname</dbms-column>
    </field-map>
    <field-map>
    <cmp-field>svcID</cmp-field>
    <dbms-column>svcid</dbms-column>
    </field-map>
    </weblogic-rdbms-bean>
    </weblogic-rdbms-jar>
    thanks a lot!

    Try this
    SELECT OBJECT(a) FROM SVCBean a WHERE a.svcName = ?1

  • Client Program accessing J2EE entity Bean

    I have trouble find my Course J2EE bean from a client. (The client
    runs on the same computer but a different VM from the bean.)
    In Glassfish (Sun Application Server Nine), I set up a simple
    Container-Managed Entity Bean. I tried to access it from an external
    client as described in the glassfish EJB
    FAQ https://glassfish.dev.java.net/javaee5/ejb/EJB-FAQ.html
    Here is the client program:
    package RS;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.xml.parsers.*;
    import org.apache.xml.serialize.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import RS.CourseHome;
    import RS.CoursePK;
    import javax.naming.InitialContext;
    import javax.naming.Context;
    import javax.naming.NamingException;
    import java.rmi.RemoteException;
    import javax.rmi.*;
    import java.util.Properties;
    import Debug.*;
    public class Client {
    public static void main (String arg[]) throws IOException {
    try {
    InitialContext jndiContext = new InitialContext ();
    Debug.P("jndic ongtext" + jndiContext);
    Object o = jndiContext.lookup("RS.CourseHome");
    Debug.P("looked up object "+o + "|"+o.getClass().getName());
    RS.CourseHome home =
        (RS.CourseHome)PortableRemoteObject.narrow(o,RS.CourseHome.class);
    Debug.P("got home "+home);
    Course C = home.create(1);
    C.setName("blah");
    CoursePK PK = new CoursePK();
    PK.number=1;
    C = home.findByPrimaryKey(PK);
    Debug.P(C.getName());
    catch (java.rmi.RemoteException re) {Debug.P("Remote Exception" + re.getMessage());}
    catch (javax.naming.NamingException ne){Debug.P("Naming Exception"+ne.getMessage());}
    catch (javax.ejb.CreateException ce){Debug.P("Create Exception"+ce.getMessage());}
    catch (javax.ejb.FinderException fe){Debug.P("Finder Exception"+fe.getMessage());}
    }Here is the error message:
    Exception in thread "main" java.lang.ClassCastException
    at com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject.narrow
                       (PortableRemoteObject.java:294)
      at javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:137)
      at RS.Client.main(Client.java:26)The debugging indicates that I got the Initial Context
    and got the object but the PortableObject.narrow failed:
    jndic ongtextjavax.naming.InitialContext@1d85f79
    looked up object IOR: (huge number deleted)
    com.sun.corba.ee.impl.corba.CORBAObjectImplEarlier, I tried the version below, but based on the suggestion by Mr. Ebbert
    in the forum started "Error When running the Client Program" by sree_devi,
    I checked
    the following. I went to "Jndi Tree Browsing" from the Administrative Console
    and I found a "RS.CourseHome" entry under "ejb" I found RS.CourseHome there
    but did not see the "Course" tghat I expected to see
    Thus, I tried the version above:
    package RS;
       --- imports deleted for conciseness
    import Debug.*;
    public class Client {
    public static void main (String arg[]) throws IOException {
    try {
    InitialContext jndiContext = new InitialContext ();
    Object o = jndiContext.lookup("Course");
    CourseHome home =
        (CourseHome)PortableRemoteObject.narrow(o,CourseHome.class);
    Course C = home.create(1);
    C.setName("blah");
    CoursePK PK = new CoursePK();
    PK.number=1;
    C = home.findByPrimaryKey(PK);
    Debug.P(C.getName());
    catch (java.rmi.RemoteException re) {Debug.P("Remote Exception" + re.getMessage());}
    catch (javax.naming.NamingException ne){Debug.P("Naming Exception"+ne.getMessage());}
    catch (javax.ejb.CreateException ce){Debug.P("Create Exception"+ce.getMessage());}
    catch (javax.ejb.FinderException fe){Debug.P("Finder Exception"+fe.getMessage());}
    }When I run it, I get the following Naming Exception: Course not found
    I confirmed at the administrative console, that I have "Course" listed
    under Enterprise Applications:
    As per the ejb FAQ, I set up my $CLASSPATH so it starts as follows:
    /opt/j2ee/SUNWappserver/lib/appserv-rt.jar:
    /opt/j2ee/SUNWappserver/lib/javaee.jar:I also verifed in my domain.xml that the orb-listener-1, the default
    naming service port was at 3700.
    Here is the info on the Bean that I have running for both of the tries
    at my Client code.
    ejb-jar.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"
    version="2.1">
      <enterprise-beans>
        <entity>
           <description>Course</description>
           <display-name>CourseBean</display-name>
           <ejb-name>CourseBean</ejb-name>
           <home>RS.CourseHome</home>
           <remote>RS.Course</remote>
           <ejb-class>RS.CourseBean</ejb-class>
           <persistence-type>Container</persistence-type>
           <prim-key-class>RS.CoursePK</prim-key-class>
           <reentrant>false</reentrant>
           <abstract-schema-name>Course</abstract-schema-name>
           <cmp-field><field-name>number</field-name></cmp-field>
           <cmp-field><field-name>name</field-name></cmp-field>
        </entity>
      </enterprise-beans>
      <assembly-descriptor>
         <security-role>
            <description>Everyone</description>
           <role-name>everyone</role-name>
         </security-role>
         <method-permission>
            <unchecked/>
            <method>
               <ejb-name>CourseBean</ejb-name>
               <method-name>*</method-name>
            </method>
          </method-permission>
         <container-transaction>
            <method>
               <ejb-name>CourseBean</ejb-name>
               <method-name>*</method-name>
            </method>
            <trans-attribute>Required</trans-attribute>
         </container-transaction>
      </assembly-descriptor>
    </ejb-jar>
    Sun-ejb-jar.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 8.1 EJB 2.1//EN"
    "http://www.sun.com/software/appserver/dtds/sun-ejb-jar_2_1-1.dtd">
    <sun-ejb-jar>
      <enterprise-beans>
         <name>CourseBean</name>
         <ejb>
           <ejb-name>CourseBean</ejb-name>
           <jndi-name>Course</jndi-name>
         </ejb>
      <cmp-resource>
         <jndi-name>jdbc/__default</jndi-name>
         <create-tables-at-deploy>true</create-tables-at-deploy>
         <drop-tables-at-undeploy>true</drop-tables-at-undeploy>
      </cmp-resource>
      </enterprise-beans>
    </sun-ejb-jar>
    Course.java
    package RS;
    import java.rmi.RemoteException;
    public interface Course extends javax.ejb.EJBObject {
      public String getName() throws RemoteException;
      public void setName (String Str) throws RemoteException;
      public int getNumber() throws RemoteException;
      public void setNumber (int n) throws RemoteException;
    CourseHome.java
    package RS;
    import java.rmi.RemoteException;
    import javax.ejb.CreateException;
    import javax.ejb.FinderException;
    public interface CourseHome extends javax.ejb.EJBHome {
    public Course create(int id) throws
    CreateException,RemoteException;
    public Course findByPrimaryKey(CoursePK pk)
    throws FinderException,RemoteException;
    CourseBean.java
    package RS;
    import javax.ejb.EntityContext;
    public abstract class CourseBean implements javax.ejb.EntityBean {
    public CoursePK ejbCreate (int number) throws javax.ejb.CreateException{
      this.setNumber(number);
      return null;
    public void ejbPostCreate (int number) {
    public abstract String getName();
    public abstract void setName (String str);
    public abstract int getNumber ();
    public abstract void setNumber (int number);
    public void setEntityContext (EntityContext ctx) {}
    public void unsetEntityContext() {}
    public void ejbActivate () {}
    public void ejbPassivate () {}
    public void ejbLoad () {}
    public void ejbStore () {}
    public void ejbRemove() {}
    }Laurence L. Leff, Ph.D. Associate Professor of Computer Science
    Western Illinois University, 1 University Circle 61455, Pager: 309 367 0787
    FAX 309 298 2302

    hi s-mcgowan,
    "some other processing" comprises of printing of debug lines and publishing to the message queue using JMS. I added more debug lines so that i could see whats really happening... here is the result
    myTableHome.create(...); <----------- no exception was thrown and it returned LocalMyTable object
    print out "Insert successful"
    print out "publishing message"
    ... publish message to message queue using JMS...
    print out "Publish done"
    ... after few milliseconds...
    java.sql.BatchUpdateException: Data exception -- row already exist in index PK_MYTABLE on table MYTABLE.
    From the exception it seems like its doing a batch insert. So that seems to explain why the java.sql.BatchUpdateException is thrown few milliseconds after my call to myTableHome.create(...);
    Is it possible to disable batch update / insert? how?
    thanks in advance,
    leigh

  • Javax.naming.NameNotFoundException: error in whil calling EJB Bean

    Dear friends,
    I have created (Bean Managed Entity) a remote,home and bean objects for adding a country in a database. When i convert
    into jar and and deploy means, its working fine. But if i put into a package means it does work
    and raise "javax.naming.NameNotFoundException" error.
    i keep my files as following folder structure
    d:\siva\projects\ShopCart\
    (under this )
    CountryMas.java
    CountryHome.java
    CountryBean.java
    CountryMasPK.java
    <meta-inf>
    ejb-jar.xml
    weblogic-ejb-jar.xml
    and deployed in weblogic 6.1 using console.
    i have copied the source code here with
    Remote interface
    package ShopCart;
    import javax.ejb.*;
    import javax.rmi.*;
    public interface CountryMas extends EJBObject {
    Home Interface
    package ShopCart;
    import javax.ejb.*;
    import java.rmi.*;
    public interface CountryHome extends EJBHome {
         public CountryMas create(String Cname) throws CreateException,RemoteException;
         public CountryMas findByPrimaryKey(CountryMasPK pk) throws      
    FinderException,RemoteException;
    BEAN OBJECT
    package ShopCart;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    import javax.sql.*;
    import javax.ejb.*;
    import javax.naming.*;
    public class CountryBean implements EntityBean {
         private EntityContext ctx;
         private int CountryId;
         private String CountryName;
         public void setEntityContext(EntityContext ctx){
              this.ctx = ctx;
         public void unsetEntityContext(){
              this.ctx = null;
         public void ejbActivate(){
         public void ejbPassivate(){
         public void ejbLoad(){
         public void ejbStore(){
         public void ejbRemove(){
              Connection con = null;
              PreparedStatement ps = null ;
              try {
                   con = getConnection();
                   ps = con.prepareStatement("Delete from CountryMas where id=?");
                   ps.setInt(1,CountryId);
                   if (ps.executeUpdate() !=1) {
                        String Error = "JDBC did not create any row";
                        throw new CreateException (Error);
              }catch (Exception e){
                   System.out.println (e);
         public CountryMasPK ejbCreate(String Cname) throws CreateException {
              this.CountryName =Cname;
              Connection con = null;
              PreparedStatement ps = null ;
              try {
                   con = getConnection();
                   ps = con.prepareStatement("insert into CountryMas values(?)");
                   ps.setString (1,CountryName);
                   if (ps.executeUpdate() !=1) {
                        String Error = "JDBC did not delete any row";
                        throw new CreateException (Error);
                   con.commit();
              }catch (Exception e){
                   System.out.println (e);
              int PKid=0;
              ResultSet rs;
              PreparedStatement ps1 = null;
              try {
                   ps1 = con.prepareStatement("select max(id) as Mid from CountryMas");
                   rs = ps1.executeQuery();
                   PKid = rs.getInt("mid");
              }catch(Exception e){
                   System.out.println (e);
              return new CountryMasPK(PKid);
         public void ejbPostCreate(String Cname) throws CreateException {
         private Connection getConnection()throws SQLException {
              InitialContext initCtx = null;
              DataSource ds = null;
              try{
                   initCtx = new InitialContext ();
                   ds = (javax.sql.DataSource)
                        initCtx.lookup("java:comp/env/jdbc/ShopCartPool");
              }catch(Exception e){
                   System.out.println(e);
              return ds.getConnection();           
         public CountryMasPK ejbFindByPrimaryKey(CountryMasPK pk)throws ObjectNotFoundException {
              Connection con= null;
              PreparedStatement ps = null ;
              try{
                   con = getConnection();
                   ps = con.prepareStatement("select cname from CountryMas where id=?");
                   ps.setInt(1,pk.ID);
                   ps.executeQuery();
                   ResultSet rs= ps.getResultSet();
                   if (rs.next()){
                        this.CountryName = rs.getString(1);
              }catch(Exception e){
                   System.out.println(e);
              //return new CountryMasPK(pk.i);
              return pk;
    PRIMARY KEY OBJECT
    package ShopCart;
    import java.io.Serializable;
    public class CountryMasPK implements java.io.Serializable {
         public int ID;
         public CountryMasPK(int ID){
              this.ID =ID;
         public CountryMasPK(){
         public CountryMasPK(CountryMasPK pk){
                   this.ID = pk.ID;
         public String toString(){
                   return new Integer(ID).toString();
         public int hashCode(){
              return new Integer(ID).hashCode();
         public boolean equals(Object countrymas){
              //return ((CountryMasPK)countrymas).ID.equals(ID);
              return true;
    EJB-JAR.XML
    <?xml version="1.0"?>
    <!DOCTYPE ejb-jar PUBLIC
    '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
    'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
    <ejb-jar>
    <enterprise-beans>
    <entity>
    <ejb-name>ShopCart</ejb-name>
    <home>ShopCart.CountryHome</home>
    <remote>ShopCart.CountryMas</remote>
    <ejb-class>ShopCart.CountryBean</ejb-class>
    <persistence-type>Bean</persistence-type>
    <prim-key-class>ShopCart.CountryMasPK</prim-key-class>
    <reentrant>False</reentrant>
    <resource-ref>
    <res-ref-name>jdbc/ShopCartPool</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    </entity>
    </enterprise-beans>
    <assembly-descriptor>
    <container-transaction>
    <method>
    <ejb-name>ShopCart</ejb-name>
         <method-name>*</method-name>
    </method>
    <trans-attribute>Required</trans-attribute>
    </container-transaction>
    </assembly-descriptor>
    </ejb-jar>
    WEBLOGIC-EJB-JAR.XML
    <?xml version="1.0"?>
    <!DOCTYPE weblogic-ejb-jar PUBLIC
    '-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN'
    'http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd'>
    <weblogic-ejb-jar>
    <weblogic-enterprise-bean>
    <ejb-name>ShopCart</ejb-name>
    <reference-descriptor>
    <resource-description>
    <res-ref-name>jdbc/ShopCartPool</res-ref-name>
         <jndi-name>ShopCartDataSource</jndi-name>
    </resource-description>
    </reference-descriptor>
    <jndi-name>Country</jndi-name>
    </weblogic-enterprise-bean>
    </weblogic-ejb-jar>
    i converted jar file like this
    d:\siva\projects\> set claapath=%classpath%;.;
    cd d:\siva\projects\ShopCart > javac *.java
    cd d:\siva\projects\ShopCart > jar -cvf Sh.jar *
    cd..
    d:\siva\projects> java weblogic.ejbc ShopCart\Sh.jar ShopCart\Shop.jar
    and deployed using weblogic 6.1 console
    and client code as follows
    Client.java
    import java.io.*;
    import javax.naming.*;
    import javax.ejb.*;
    import javax.rmi.*;
    import java.util.*;
    import ShopCart.*;
    class Client {
         public static void main(String args[]){
              Context ctx=null;
              try{
                   Properties pr = new Properties();
                   pr.put(Context.INITIAL_CONTEXT_FACTORY,
                        "weblogic.jndi.WLInitialContextFactory");
                   pr.put(Context.PROVIDER_URL,"t3://localhost:7001");
                   ctx= new InitialContext(pr);
                   Object obj = ctx.lookup("Country");
                   CountryHome cm = (CountryHome)
    javax.rmi.PortableRemoteObject.narrow(obj,CountryHome.class);
                   cm.create(args[0]);
                   System.out.println ("Creating Country " + args[0] +" ..... [Done]");          
              }catch (Exception e){
                   System.out.println(e);
    when i run this file it raise the error
    D:\Siva\Projects>java Client.java
    Exception in thread "main" java.lang.NoClassDefFoundError: Client/java
    D:\Siva\Projects>java Client
    javax.naming.NameNotFoundException: Unable to resolve Country. Resolved: '' Unre
    solved:'Country' ; remaining name ''
    D:\Siva\Projects>
    This is the error message. Please observe it and do let me know what would be the error. There
    would be small configuration error. But i couldn't locate it . plz help me somebody.
    Thanx & Regards,
    Siva.

    you need to use the name java:comp/env/Country in the client.
    and the client deployment descriptor will need an ejb-ref entry:
    <ejb-ref>
      <ejb-ref-name>
        Country
      </ejb-ref-name>
      <ejb-ref-type>
        Session
      </ejb-ref-type>
      <home>
        ShopCart.CountryHome
      </home>
      <remote>
        ShopCart.CountryMas
      </remote>
    </ejb-ref>toby

  • Dependent Object persistence in EJB 1.1

    Please take a look at the following container-managed entity EJB
    code:
    //REMOTE INTERFACE //----------------------
    import javax.ejb.EJBObject;
    import java.rmi.RemoteException;
    public interface Product extends EJBObject {
    public void setPrice(double price) throws RemoteException;
    public double getPrice() throws RemoteException;
    public String getDescription() throws RemoteException;
    public void setDescription(String desc) throws RemoteException;
    public ItemView getItemView() throws RemoteException;
    public void setItemView(ItemView i) throws RemoteException;
    //HOME INTERFACE //------------------------------
    import java.util.Collection;
    import java.rmi.RemoteException;
    import javax.ejb.*;
    public interface ProductHome extends EJBHome {
    public Product create(String productId, String description,
    double balance, ItemView itemView) throws RemoteException,
    CreateException;
    public Product findByPrimaryKey(String productId)
    throws FinderException, RemoteException;
    public Collection findByDescription(String description)
    throws FinderException, RemoteException;
    public Collection findInRange(double low, double high)
    throws FinderException, RemoteException;
    //EJBean //----------------------------------------------
    import java.util.*;
    import javax.ejb.*;
    public class ProductBean implements EntityBean {
    public String productId;
    public String description;
    public double price;
    //custom java class: Item
    public Item item;
    private EntityContext context;
    public void setPrice(double price) {
    this.price = price;
    public double getPrice() {
    return price;
    //instead of returning field Item, an object of ItemView with Item
    data is returned.
    public ItemView getItemView()
    return new ItemView(item.getDesc(), item.getCodeNum());
    public void setItemView(ItemView itemView)
    this.item = new Item(itemView.getDView(), itemView.getCView
    public String getDescription() { return description; }
    public void setDescription(String descri) {description = descri;}
    public String ejbCreate(String productId, String description,
    double price, ItemView itemView) throws CreateException {
    if (productId == null) {
    throw new CreateException("The productId is required.");
    this.productId = productId;
    this.description = description;
    this.price = price;
    item = new Item(itemView.getDView(), itemView.getCView());
    return null;
    public void setEntityContext(EntityContext context) {
    this.context = context;
    public void ejbActivate() {
    productId = (String)context.getPrimaryKey();
    public void ejbPassivate() {
    productId = null;
    description = null;
    public void ejbRemove() { }
    public void ejbLoad() { }
    public void ejbStore() { }
    public void unsetEntityContext() { }
    public void ejbPostCreate(String productId, String description,
    double balance, ItemView itemView) { System.out.println
    ("ProductBean ejbPostCreate"); }
    } // End of ProductBean
    //Item //-------------
    public class Item implements java.io.Serializable {
    public String desc;
    public int codeNum;
    public Item(String desc, int CodeNum) {
    desc = desc;
    codeNum = codeNum;
    public void setDesc(String decs) {desc = desc;}
    public void setCodeNum(int i) {codeNum = codeNum;}
    public String getDesc() {return desc;}
    public int getCodeNum(){return codeNum;}
    } //End of Item
    //ItemView //-------------------------------------
    public class ItemView implements java.io.Serializable {
    public String dView;
    public int cView;
    public ItemView(String s, int i) {
    dView = s;
    cView = i;
    public void setDView(String s) {dView = s;}
    public String getDView() {return dView; }
    public void setCView(int i) {cView = i;}
    public int getCView() {return cView;}
    Upon running the following client:
    //ProductClient //-------------------------------------
    import java.util.*;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.rmi.PortableRemoteObject;
    public class ProductClient {
    public static void main(String[] args) {
    try {
    Context initial = new InitialContext();
    Object objref = initial.lookup("MyProduct123");
    ProductHome home =
    (ProductHome)PortableRemoteObject.narrow(objref,
    ProductHome.class);
    Product duke = home.create("1006", "Siamese atty", 23.13,
    new ItemView("Hot",12));
    System.out.println("Description: " + duke.getDescription());
    System.out.println("Price: "+ duke.getPrice());
    System.out.println("Item desc: " + duke.getItemView
    ().getDView());
    System.out.println("Item CodeNum: " + duke.getItemView
    ().getCView());
    } catch (Exception ex) {
    System.err.println("Caught an exception." );
    ex.printStackTrace();
    This is expected to create a ProductBean whose Item field variable
    object will have "Hot" and 12 as its values. However, the program
    output is:
    Description: Ceramic Catty
    Price: 19.23
    Item desc: null
    Item CodeNum: 0
    1. I am unable to understand why the Item object contained in the
    ProductBean remains null.
    2. I read in a sdmagazine article, that helper objects (dependent
    objects) should not be exposed directly to the client. I have used
    the ItemView in line with this argument although I am not clear if
    this is a requirement , if so, what is the rationale behind it.
    Please see
    http://www.sdmagazine.com/documents/s=739/sdm0010j/0010j.htm.
    3. If I do not use ItemView and expose the Item field directly to the
    client, there is a runtime error NullPointerExc eption...
    4. Does EJB 2.0 adopts the same approach i.e. can depenmdent objects
    be directly exposed to the client or not. Or this is just a
    recommendation not a requirement?
    In the above mentioned article :
    (http://www.sdmagazine.com/documents/s=739/sdm0010j/0010j.htm)
    "EJB enables me to improve the design I presented in Figure 1. The
    problem is the address attribute; it's an object and not a primitive
    value. Because I need to persist addresses, I have two options: I can
    implement it as a dependent value object or as a dependent object. A
    dependent value object is one that is serializable, the properties of
    which are saved as a single value; it's the relational database
    equivalent of a binary large object (blob). On the other hand, the
    properties of dependent objects are saved as individual values, one
    for each property. This appears to be a significant advantage, but it
    comes at a price: A dependent object must never be directly exposed
    to the clients of entity beans via its remote interface because the
    persistence container is free to optimize the delivery of dependent
    objects and may never fully materialize them as full-fledged classes.
    What you should do, as Figure 2 indicates, is expose a representation
    of the dependent object if required. I have done this with the new
    versions of the getAddress() and setAddress() operations in the
    Customer class that now work with instances of XmlDocument instead of
    Address. A little clunky, but reasonably easy to live with in
    practice. Note that I didn't have to introduce any code to maintain
    the relationship between the two classes to my model."
    5. This is totally new to me. I don't know what the author means when
    he says 'the properties of
    which (dependent object) are saved as individual values, one for each
    property.' Does this mean,
    the dependent object can be persisted in a separate table. How is it
    possible while using CMP? 6.
    And 'all this comes at a price...' I can't see what's the price.
    Any help is highly appreciated.
    Regards,
    Hasan

    Did you forget adding "this." in the item.java.

  • Deploying Entity Bean Managed Persistant Example.

    Here is my error after running the client:
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException; nested exception is:
    javax.transaction.RollbackException
    at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:170)
    at javax.rmi.CORBA.Util.mapSystemException(Util.java:65)
    at Test1HomeStub.create(Unknown Source)
    at Test1Client.main(Unknown Source)
    Here is the J2EE Verification error (allthough it deploys sucessfully I get this error for all the
    tuitorial examples)
    Error: [ ejb/SimpleTest1 ] class [ Test1Home ] cannot be found within this jar [ app-client-ic.jar ].
    For [ app-client-ic.jar ]
    Error: [ ejb/SimpleTest1 ] class [ Test1 ] cannot be found within this jar [ app-client-ic.jar ].
    I have edited the SavingsAccount example so it has only got one table, two fields and a couple of methods. Here is the code:
    create.sql
    drop table test1;
    create table test1
    (id varchar(3) constraint pk_test1 primary key,
    firstname varchar(24) );
    exit;
    Test!Bean.java
    import java.sql.*;
    import javax.sql.*;
    import java.util.*;
    import javax.ejb.*;
    import javax.naming.*;
    public class Test1Bean implements EntityBean {
    private final static String dbName = "java:comp/env/jdbc/Test1DB";
    private String id;
    private String firstName;
    private EntityContext context;
    private Connection con;
    public String getFirstName() {
    return firstName;
    public String ejbCreate(String id, String firstName) throws CreateException {
    try {
    insertRow(id, firstName);
    } catch (Exception ex) {
    throw new EJBException("ejbCreate: " + ex.getMessage());
    this.id = id;
    this.firstName = firstName;
    return id;
    public String ejbFindByPrimaryKey(String primaryKey)
    throws FinderException {
    boolean result;
    try {
    result = selectByPrimaryKey(primaryKey);
    } catch (Exception ex) {
    throw new EJBException("ejbFindByPrimaryKey: " + ex.getMessage());
    if (result) {
    return primaryKey;
    } else {
    throw new ObjectNotFoundException("Row for id " + primaryKey +
    " not found.");
    public void ejbRemove() {
    try {
    deleteRow(id);
    } catch (Exception ex) {
    throw new EJBException("ejbRemove: " + ex.getMessage());
    public void setEntityContext(EntityContext context) {
    this.context = context;
    public void unsetEntityContext() {
    public void ejbActivate() {
    id = (String) context.getPrimaryKey();
    public void ejbPassivate() {
    id = null;
    public void ejbLoad() {
    try {
    loadRow();
    } catch (Exception ex) {
    throw new EJBException("ejbLoad: " + ex.getMessage());
    public void ejbStore() {
    try {
    storeRow();
    } catch (Exception ex) {
    throw new EJBException("ejbStore: " + ex.getMessage());
    public void ejbPostCreate(String id, String firstName) {
    /*********************** Database Routines *************************/
    private void makeConnection() {
    try {
    InitialContext ic = new InitialContext();
    DataSource ds = (DataSource) ic.lookup(dbName);
    con = ds.getConnection();
    } catch (Exception ex) {
    throw new EJBException("Unable to connect to database. " +
    ex.getMessage());
    private void releaseConnection() {
    try {
    con.close();
    } catch (SQLException ex) {
    throw new EJBException("releaseConnection: " + ex.getMessage());
    private void insertRow(String id, String firstName) throws SQLException {
    makeConnection();
    String insertStatement =
    "insert into test1 values ( ? , ? )";
    PreparedStatement prepStmt = con.prepareStatement(insertStatement);
    prepStmt.setString(1, id);
    prepStmt.setString(2, firstName);
    prepStmt.executeUpdate();
    prepStmt.close();
    releaseConnection();
    private void deleteRow(String id) throws SQLException {
    makeConnection();
    String deleteStatement = "delete from test1 where id = ? ";
    PreparedStatement prepStmt = con.prepareStatement(deleteStatement);
    prepStmt.setString(1, id);
    prepStmt.executeUpdate();
    prepStmt.close();
    releaseConnection();
    private boolean selectByPrimaryKey(String primaryKey)
    throws SQLException {
    makeConnection();
    String selectStatement =
    "select id " + "from test1 where id = ? ";
    PreparedStatement prepStmt = con.prepareStatement(selectStatement);
    prepStmt.setString(1, primaryKey);
    ResultSet rs = prepStmt.executeQuery();
    boolean result = rs.next();
    prepStmt.close();
    releaseConnection();
    return result;
    private void loadRow() throws SQLException {
    makeConnection();
    String selectStatement =
    "select firstname from test1 where id = ? ";
    PreparedStatement prepStmt = con.prepareStatement(selectStatement);
    prepStmt.setString(1, this.id);
    ResultSet rs = prepStmt.executeQuery();
    if (rs.next()) {
    this.firstName = rs.getString(1);
    prepStmt.close();
    } else {
    prepStmt.close();
    throw new NoSuchEntityException("Row for id " + id +
    " not found in database.");
    releaseConnection();
    private void storeRow() throws SQLException {
    makeConnection();
    String updateStatement =
    "update test1 set firstname = ? where id = ?";
    PreparedStatement prepStmt = con.prepareStatement(updateStatement);
    prepStmt.setString(1, firstName);
    prepStmt.setString(4, id);
    int rowCount = prepStmt.executeUpdate();
    prepStmt.close();
    if (rowCount == 0) {
    throw new EJBException("Storing row for id " + id + " failed.");
    releaseConnection();
    // Test1Bean
    Test1Client
    import java.util.*;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.rmi.PortableRemoteObject;
    public class Test1Client {
    public static void main(String[] args) {
    try {
    Context initial = new InitialContext();
    Object objref =
    initial.lookup("java:comp/env/ejb/SimpleTest1");
    Test1Home home =
    (Test1Home) PortableRemoteObject.narrow(objref,
    Test1Home.class);
    Test1 duke =
    home.create("123", "Duke");
    duke = home.findByPrimaryKey("123");
    System.out.println(duke.getFirstName());
    System.exit(0);
    catch (Exception ex)
    System.err.println("Caught an exception.");
    ex.printStackTrace();
    Test1Home.jav
    import java.rmi.RemoteException;
    import javax.ejb.*;
    public interface Test1Home extends EJBHome {
    public Test1 create(String id, String firstName) throws RemoteException, CreateException;
    public Test1 findByPrimaryKey(String id)
    throws FinderException, RemoteException;
    Test1.java
    import javax.ejb.EJBObject;
    import java.rmi.RemoteException;
    public interface Test1 extends EJBObject {
    public String getFirstName() throws RemoteException;
    application.xml (Test1App.ear)
    <?xml version="1.0" encoding="UTF-8"?>
    <application xmlns="http://java.sun.com/xml/ns/j2ee" version="1.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application_1_4.xsd">
    <description>Application description</description>
    <display-name>Test1App</display-name>
    <module>
    <java>app-client-ic.jar</java>
    </module>
    <module>
    <ejb>ejb-jar-ic.jar</ejb>
    </module>
    </application>
    sun-application.xml (Test1App.ear)
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-application PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 8.0 J2EE Application 1.4//EN" "http://www.sun.com/software/appserver/dtds/sun-application_1_4-0.dtd">
    <sun-application>
    <pass-by-reference>false</pass-by-reference>
    </sun-application>
    ejb-jar.xml (in ejb-jar-ic.jar)
    <?xml version="1.0" encoding="UTF-8"?>
    <ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" version="2.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">
    <display-name>Test1JAR</display-name>
    <enterprise-beans>
    <entity>
    <ejb-name>Test1Bean</ejb-name>
    <home>Test1Home</home>
    <remote>Test1</remote>
    <ejb-class>Test1Bean</ejb-class>
    <persistence-type>Bean</persistence-type>
    <prim-key-class>java.lang.String</prim-key-class>
    <reentrant>true</reentrant>
    <resource-ref>
    <res-ref-name>jdbc/Test1DB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    <security-identity>
    <use-caller-identity/>
    </security-identity>
    </entity>
    </enterprise-beans>
    <assembly-descriptor>
    <method-permission>
    <unchecked/>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Home</method-intf>
    <method-name>remove</method-name>
    <method-params>
    <method-param>java.lang.Object</method-param>
    </method-params>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Home</method-intf>
    <method-name>getHomeHandle</method-name>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>isIdentical</method-name>
    <method-params>
    <method-param>javax.ejb.EJBObject</method-param>
    </method-params>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>getFirstName</method-name>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Home</method-intf>
    <method-name>findByPrimaryKey</method-name>
    <method-params>
    <method-param>java.lang.String</method-param>
    </method-params>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Home</method-intf>
    <method-name>remove</method-name>
    <method-params>
    <method-param>javax.ejb.Handle</method-param>
    </method-params>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>getHandle</method-name>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Home</method-intf>
    <method-name>create</method-name>
    <method-params>
    <method-param>java.lang.String</method-param>
    <method-param>java.lang.String</method-param>
    </method-params>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Home</method-intf>
    <method-name>getEJBMetaData</method-name>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>getPrimaryKey</method-name>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>remove</method-name>
    </method>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>getEJBHome</method-name>
    </method>
    </method-permission>
    <container-transaction>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>remove</method-name>
    </method>
    <trans-attribute>Required</trans-attribute>
    </container-transaction>
    <container-transaction>
    <method>
    <ejb-name>Test1Bean</ejb-name>
    <method-intf>Remote</method-intf>
    <method-name>getFirstName</method-name>
    </method>
    <trans-attribute>Required</trans-attribute>
    </container-transaction>
    </assembly-descriptor>
    </ejb-jar>
    sun-ejb-jar.xml (in ejb-jar-ic.jar )
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 8.0 EJB 2.1//EN" "http://www.sun.com/software/appserver/dtds/sun-ejb-jar_2_1-0.dtd">
    <sun-ejb-jar>
    <enterprise-beans>
    <name>Test1JAR</name>
    <ejb>
    <ejb-name>Test1Bean</ejb-name>
    <jndi-name>Test1Bean</jndi-name>
    <resource-ref>
    <res-ref-name>jdbc/Test1DB</res-ref-name>
    <jndi-name>jdbc/ejbTutorialDB</jndi-name>
    </resource-ref>
    </ejb>
    </enterprise-beans>
    </sun-ejb-jar>
    application-client.xml ( in app-client-ic.jar)
    <?xml version="1.0" encoding="UTF-8"?>
    <application-client xmlns="http://java.sun.com/xml/ns/j2ee" version="1.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application-client_1_4.xsd"><display-name>Test1Client</display-name>
    <ejb-ref>
    <ejb-ref-name>ejb/SimpleTest1</ejb-ref-name>
    <ejb-ref-type>Entity</ejb-ref-type>
    <home>Test1Home</home>
    <remote>Test1</remote>
    </ejb-ref>
    </application-client>
    sun-application-client.xml ( in app-client-ic.jar)
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-application-client PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 8.0 Application Client 1.4//EN" "http://www.sun.com/software/appserver/dtds/sun-application-client_1_4-0.dtd">
    <sun-application-client>
    <ejb-ref>
    <ejb-ref-name>ejb/SimpleTest1</ejb-ref-name>
    <jndi-name>Test1Bean</jndi-name>
    </ejb-ref>
    </sun-application-client>
    This is adapted from the Savings Account example. I couldn't get it to work either
    from the source provided though it did work with the provided ear. I have been
    comparing the difference in setting but can see anything.
    I have been able to build and deploy all the other examples in the tutorial but I am somehow
    stuck on ejbs.
    Help would be much appreciated.
    cheers,
    paul

    Just had a look at the client jar. The one generated by the Savings Account provided ear has got a shorter ejb-jar.xml. It doesn't have the functions specified like the one in its ear file.
    Another difference thet the Manifest.mf files for my client jar do not have as many paths specified
    as my test client jar. Don't know why. I am suspecting that maybe there is a slight configuration problem in my j2ee setup. Though I am not sure waht or what to look for. I hope this little bit of
    extra info helps.
    cheers,
    paul.

  • MSAccess Count Field incorrect problem

    Hello I am trying an update of Details, I traced the code along to it populated fields and verified values as correct.I am getting an error on the
    int resultCount = stmt.executeUpdate();
                if ( resultCount != 1 ) {Why is this ?
    My error line is :ClubBean: message = Unable to update item Swing
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
    ClubBean: Fatal Error Occurred
    Please tell me if what i am trying to do is wrong.
    * ClubDAO.java
    * Created on 31 March 2004, 14:45
    package com.soundstage;
    * @author  Andrew
    import java.io.*;
    import java.sql.*;
    import java.text.*;
    import java.util.*;
    import javax.sql.*;
    public class ClubDAO implements Serializable, DataAccess {
        private transient TransactionContext globalTran = null;
        private transient ClubValue clubVal   = null;
         *Creates a new instance of DAO
        public ClubDAO(TransactionContext transactionContext) {
            globalTran = transactionContext;
        public Object findByPrimaryKey(Integer memberNumber)
        throws DAOSysException, DAOFinderException {
            if (itemExistsById(memberNumber)) {
                //log("CustomerDAO: returning " + clubVal.getMemberNumber());
                return clubVal;
            throw new DAOFinderException("Club Not Found = "
            + memberNumber);
        public void deleteObject(Integer id) throws DAOSysException,
        DAODBUpdateException{
            String queryStr = "DELETE FROM " + "Club" +
            " WHERE ClubName = "
            + id;
            log("queryString is: "+ queryStr);
            Statement stmt = null;
            try {
                stmt = globalTran.getDBConnection().createStatement();
                int resultCount = stmt.executeUpdate(queryStr);
                if ( resultCount != 1 )
                    throw new DAODBUpdateException("ERROR deleteing Club from" + " Club_TABLE!! resultCount = " + resultCount);
            } catch(SQLException se) {
                throw new DAOSysException("Unable to delete for item " + id + "\n" + se);
            } finally {
                globalTran.closeStatement(stmt);
                log("ClubDAO: closeStatement");
        public void deleteObject(String clubName)
        throws DAOSysException, DAODBUpdateException {
            String queryStr = "DELETE FROM Club WHERE ClubName = " + "'"+clubName+"'";
            log("queryString is: "+ queryStr);
            Statement stmt = null;
            try {
                stmt = globalTran.getDBConnection().createStatement();
                int resultCount = stmt.executeUpdate(queryStr);
                if ( resultCount != 1 )
                    throw new DAODBUpdateException("ERROR deleteing Club from" + " Club_TABLE!! resultCount = " + resultCount);
            } catch(SQLException se) {
                throw new DAOSysException("Unable to delete for item " + clubName + "\n" + se);
            } finally {
                globalTran.closeStatement(stmt);
                log("ClubDAO: closeStatement");
        public void updateObject(Object model) throws
        DAOAppException, DAODBUpdateException,
        DAOSysException{
            ClubValue clubVal = (ClubValue) model;
            PreparedStatement stmt = null;
            try {
                String queryStr = "UPDATE " + "Club" +
                  " SET " + "ClubName = ?, " +
                  "NumberOfMembersEnrolled = ?, " +
                  "NumberOfCancelledYTD = ?, " +
                  "CurrentPromotion = ?, " +
                  "TotalUnitsSoldForClub = ?, " +
                  "MaximumPeriodOfObligation = ?, " +
                  "WHERE ClubName = ?";
                log("ClubDAO: Update String " + queryStr);
                stmt = globalTran.getDBConnection().prepareStatement(queryStr);
                log("ClubDAO: Prepare Worked ");
                stmt.setString(1, clubVal.getClubName());
                stmt.setInt(2, clubVal.getNumberOfMembersEnrolled());
                stmt.setInt(3, clubVal.getNumberOfCancelledYTD());
                stmt.setString(4, clubVal.getCurrentPromotion());
                stmt.setInt(5, clubVal.getTotalUnitsSoldForClub());
                stmt.setInt(6, clubVal.getMaximumPeriodOfObligation());
                log("ClubDAO: done setting items ");
                int resultCount = stmt.executeUpdate();
                if ( resultCount != 1 ) {
                    log("ClubDAO: update failed");
                    throw new DAODBUpdateException ("ERROR updating ClubD in" + " Club!! resultCount = " + resultCount);
                log("ClubDAO: update worked...result count = " + resultCount);
            } catch(SQLException se) {
                throw new DAOSysException("Unable to update item " + clubVal.getClubName() + " \n" + se);
            } finally {
                globalTran.closeStatement(stmt);
                log("ClubDAO: closeStatement");
        public void insertObject(Object model) throws
        DAOAppException, DAODBUpdateException,
        DAOSysException{
            ClubValue clubVal = (ClubValue) model;
            PreparedStatement stmt = null;
            try {
                String queryStr = "INSERT INTO Club (ClubName, NumberOfMembersEnrolled, NumberOfCancelledYTD, CurrentPromotion," +
                "TotalUnitsSoldForClub, MaximumPeriodOfObligation)" +
                "VALUES (?, ?, ?, ?, ?, ?)";
                log("ClubDAO: Insert String " + queryStr);
                stmt = globalTran.getDBConnection().
                prepareStatement(queryStr);
                int i = 1;
                stmt.setString(i++, clubVal.getClubName());
                stmt.setInt(i++, clubVal.getNumberOfMembersEnrolled());
                stmt.setInt(i++, clubVal.getNumberOfCancelledYTD());
                stmt.setString(i++, clubVal.getCurrentPromotion());
                stmt.setInt(i++, clubVal.getTotalUnitsSoldForClub());
                stmt.setInt(i++, clubVal.getMaximumPeriodOfObligation());
                int resultCount = stmt.executeUpdate();
                if ( resultCount != 1 )
                    throw new DAODBUpdateException("ERROR inserting Club in" + " Club!! resultCount = " + resultCount);
            } catch(SQLException se) {
                throw new DAOSysException("Unable to insert item " + clubVal.getClubName() + " \n" + se);
            } finally {
                globalTran.closeStatement(stmt);
                log("ClubDAO: closeStatement");
         * Returns an CustomerValue initialized with the information
         * found in the database for the specified customer, or null if
         * not found.
        public Object findByName(String name)
        throws DAOSysException, DAOFinderException {
            //log("CustomerDAO: start findByCustomerNumber");
            if (itemExistsByName(name)) {
                //  log("ClubDAO: returning " + clubVal.getCustomerId());
                return clubVal;
            throw new DAOFinderException("Club Not Found = "
            + name);
        private boolean itemExistsById(Integer memberNumber) throws DAOSysException {
            String queryStr ="SELECT MemberNumber, MemberName, " +
            "FROM member " +
            "WHERE MemberNumber = " + memberNumber;
            return doQuery(queryStr);
        private boolean itemExistsByName(String clubName) throws DAOSysException {
            //  log("MemberDAO: before query creation");
            String queryStr ="SELECT * FROM Club WHERE ClubName = " + "'"+clubName+"'";
            log(queryStr);
            return doQuery(queryStr);
        private boolean doQuery(String qryString) throws DAOSysException {
            Statement stmt = null;
            ResultSet result = null;
            boolean returnValue = false;
            try {
                //  log("CustomerDAO: before statement creationg");
                stmt = globalTran.getDBConnection().createStatement();
                // log("CustomerDAO: statement created");
                //log("CustomerDAO: query is" + qryString);
                result = stmt.executeQuery(qryString);
                // log("CustomerDAO: statement executed");
                if ( !result.next() ) {
                    //log("CustomerDAO: customer not found");
                    returnValue = false;
                else {
                    // log("CustomerDAO: Club found");
                    clubVal = new ClubValue();
                    int i = 1;
                    clubVal.setClubName(result.getString(i++));
                    clubVal.setNumberOfMembersEnrolled(result.getInt(i++));
                    clubVal.setNumberOfCancelledYTD(result.getInt(i++));
                    clubVal.setCurrentPromotion(result.getString(i++));
                    clubVal.setTotalUnitsSoldForClub(result.getInt(i++));
                    clubVal.setMaximumPeriodOfObligation(result.getInt(i++));
                    returnValue = true;
            } catch(SQLException se) {
                se.printStackTrace();
                throw new DAOSysException("Unable to Query for item " +
                "\n" + se);
            } finally {
                // log("CustomerDAO: prior");
                globalTran.closeResultSet(result);
                // log("CustomerDAO: closeResult");
                globalTran.closeStatement(stmt);
                // log("CustomerDAO: closeStatement");
            return returnValue;
        private void closeResultSet(ResultSet result) throws DAOSysException {
            try {
                if (result != null) {
                    result.close();
            } catch (SQLException se) {
                throw new DAOSysException("SQL Exception while closing " +
                "Result Set : \n" + se);
        private void closeStatement(Statement stmt) throws DAOSysException {
            try {
                if (stmt != null) {
                    stmt.close();
            } catch (SQLException se) {
                throw new DAOSysException("SQL Exception while closing " +
                "Statement : \n" + se);
        private void log(String s) {
            System.out.println(s);
    }Thank You

    Sorry its the UpdateObject.
    public void updateObject(Object model) throws
        DAOAppException, DAODBUpdateException,
        DAOSysException{
            ClubValue clubVal = (ClubValue) model;
            PreparedStatement stmt = null;
            try {
                String queryStr = "UPDATE " + "Club" +
                  " SET " + "ClubName = ?, " +
                  "NumberOfMembersEnrolled = ?, " +
                  "NumberOfCancelledYTD = ?, " +
                  "CurrentPromotion = ?, " +
                  "TotalUnitsSoldForClub = ?, " +
                  "MaximumPeriodOfObligation = ?, " +
                  "WHERE ClubName = ?";
                log("ClubDAO: Update String " + queryStr);
                stmt = globalTran.getDBConnection().prepareStatement(queryStr);
                log("ClubDAO: Prepare Worked ");
                stmt.setString(1, clubVal.getClubName());
                stmt.setInt(2, clubVal.getNumberOfMembersEnrolled());
                stmt.setInt(3, clubVal.getNumberOfCancelledYTD());
                stmt.setString(4, clubVal.getCurrentPromotion());
                stmt.setInt(5, clubVal.getTotalUnitsSoldForClub());
                stmt.setInt(6, clubVal.getMaximumPeriodOfObligation());
                log("ClubDAO: done setting items ");
                int resultCount = stmt.executeUpdate();
                if ( resultCount != 1 ) {
                    log("ClubDAO: update failed");
                    throw new DAODBUpdateException ("ERROR updating ClubD in" + " Club!! resultCount = " + resultCount);
                log("ClubDAO: update worked...result count = " + resultCount);
            } catch(SQLException se) {
                throw new DAOSysException("Unable to update item " + clubVal.getClubName() + " \n" + se);
            } finally {
                globalTran.closeStatement(stmt);
                log("ClubDAO: closeStatement");
        }

  • Entity bean mapping to multiple tables.

    Hello,
    Is it possible to map several tables with only one BMP?
    if so please send me an example (class bean)
    Thanks in advance

    hi,
    yes, entity bean can be mapped to multiple tables provided it is bean managed entity bean.
    since, container cannot prepare complex quries so that we need to rely on bean managed persistance.
    Ex : Assume you have two table like X, Y
    where X table having fields (int x primarykey, varchar str) and Y table having fields (varchar name primarykey, int y).
    Now you should design a primary key class of your own as shown below:
    public class BeanPriamkey implements java.io.Serializable
    protected int x;
    protected String name;
    public BeanPramkey()
    //initialzation part
    public BeanPramkey(int x,String str)
    //initialzation part
    public String toString()
    //return object value as string
    public int hashCode()
    //return an int value
    public boolean equals(BeanPramkey)
    public int getX()
    return x;
    public String getStr()
    return str;
    now your entity bean would be like this
    public class Mybean implements EntityBean
    int x,y;
    String str,name;
    BeanPriamkey primekey;
    public BeanPrrmkey ejbCreate(int x,String name)
    //fetch the rows from the tables X and Y ;
    //if the rows exists int the tables create beanprimkey object with x and name and return refernce of the Beanprimkey class object
    public BeanPrimkey findByPrimarykey(BeanPrimkey )
    //first extract values of x and str from BeanPrimkey
    and chek X and Y table for corresponding rows if exists return the reference of BeanPrimkey else return null
    public void ejbStore()
    BeanPrimkey prikey = (BeanPrimkey) entityContext.getPrimarykey();
    int x = prikey.getX();
    String st = prikey.getStr();
    update X and Y tables using x and str;
    public void ejbLoad()
    BeanPrimkey prikey = (BeanPrimkey) entityContext.getPrimarykey();
    int x = prikey.getX();
    String st = prikey.getStr();
    fetch the rows from X and Y tables using x and str;
    and assing the row values to bean instance variables.
    public void ejbPassivate()
    //code for release the resources
    public void ejbActivate()
    //code for aquiring the resource
    public void setEntityContext(EntityContext ec)
    this.ec = ec;
    protected EntityContext ec;

  • Help with EJB plz

    Hi,
    I'm new to EBJs and am playing with an entity bean pretty much identical to the one on the J2EE tutorial but the home interface does not compile and I've got no idea why. Would really appreciate your help.
    COMPILER COMPLAINT*****
    C:\j2sdkee1.3\nim\src\ejb\addresses>javac AddressesHome.java
    AddressesHome.java:7: cannot resolve symbol
    symbol : class Addresses
    location: interface AddressesHome
    public Addresses Create(String id, String firstname, String lastname, St
    ring address, int contactno) throws RemoteException, CreateException;
    ^
    AddressesHome.java:10: cannot resolve symbol
    symbol : class Addresses
    location: interface AddressesHome
    public Addresses FindByPrimaryKey(String id) throws FinderException, Rem
    oteException;
    ^
    2 errors
    HOME INTERFACE*****
    import java.util.Collection;
    import java.rmi.RemoteException;
    import javax.ejb.*;
    public interface AddressesHome extends EJBHome
         public Addresses Create(String id, String firstname, String lastname, String address, int contactno) throws RemoteException, CreateException;
         public Addresses FindByPrimaryKey(String id) throws FinderException, RemoteException;
         public Collection FindByLastName(String lastname) throws FinderException, RemoteException;
    ADDRESSESSBEAN CLASS*****
    import java.sql.*;
    import javax.sql.*;
    import java.util.*;
    import javax.ejb.*;
    import javax.naming.*;
    public class AddressesBean implements EntityBean
         private String id;
         private String firstname;
         private String lastname;
         private String address;
         private int contactno;
         private Connection conn;
         private EntityContext context;
         private String dbName = "java:comp/env/jdbc/AddressesdB";
         public String ejbCreate(String id, String firstname, String lastname, String address, int contactno) throws CreateException
                   if(address == null || address.length() == 0)
                        throw new CreateException("You must specify an address");
                   try
                        insertRow(id, firstname, lastname, address, contactno);
                   catch(Exception e)
                        throw new EJBException("ejbCreate: " + e.getMessage());
                   this.id = id;
                   this.firstname = firstname;
                   this.lastname = lastname;
                   this.address = address;
                   this.contactno = contactno;
                   return id;
         public void changeAddress(String address)
              this.address = address;
         public String getAddress()
              return address;
         public void changeContactno(int contactno)
              this.contactno = contactno;
         public int getContactno()
              return contactno;
         public String getFirstname()
              return firstname;
         public String getLastname()
              return lastname;
         public String ejbFindByPrimaryKey(String primaryKey) throws FinderException
              boolean result;
              try
                   result = selectByPrimaryKey(primaryKey);
              catch(Exception e)
                   throw new EJBException("ejbFindByPrimaryKey: " + e.getMessage());
              if(result)
                   return primaryKey;
              else
                   throw new ObjectNotFoundException("Row for id " + primaryKey + " not found");
         public Collection ejbFindByLastName(String lastname) throws FinderException
              Collection result;
              try
                   result = selectByLastName(lastname);
              catch(Exception e)
                   throw new FinderException("ejbFindByLastName :" + e.getMessage());
              return result;
         public void ejbRemove()
              try
                   deleteRow(id);
              catch(Exception e)
                   throw new EJBException("ejbRemove : " + e.getMessage());
         public void setEntityContext(EntityContext context)
              this.context = context;
              try
                   makeConnection();
              catch(Exception e)
                   throw new EJBException("Unable to connect to database: " + e.getMessage());
         public void unsetEntityContext()
              try
                   conn.close();
              catch(Exception e)
                   throw new EJBException("unsetEntityContext: " + e.getMessage());
         public void ejbActivate()
              id = (String)context.getPrimaryKey();
         public void ejbPassivate()
              id = null;
         public void ejbLoad()
              try
                   loadRow();
              catch(Exception e)
                   throw new EJBException("ejbLoad: " + e.getMessage());
         public void ejbStore()
              try
                   storeRow();
              catch(Exception e)
                   throw new EJBException("ejbStore: " + e.getMessage());
         public void ejbPostCreate(String id, String firstname, String lastname, String address, boolean contactno)
         /****************************** DataBase Routines ******************************/
         private void makeConnection() throws NamingException, SQLException
              InitialContext ic = new InitialContext();
              DataSource ds = (DataSource) ic.lookup(dbName);
              conn = ds.getConnection();
         private void insertRow(String id, String firstname, String lastname, String address, int contactno) throws SQLException
              String insertStatement = "inset into ADDRESSES values (?, ?, ?, ?, ?)";
              PreparedStatement prepStmt = conn.prepareStatement(insertStatement);
              prepStmt.setString(1, id);
              prepStmt.setString(2, firstname);
              prepStmt.setString(3, lastname);
              prepStmt.setString(4, address);
              prepStmt.setDouble(5, contactno);
              prepStmt.executeUpdate();
              prepStmt.close();
         private void deleteRow(String id) throws SQLException
              String deleteStatement = "delete from ADDRESSES where id = ?";
              PreparedStatement prepStmt = conn.prepareStatement(deleteStatement);
              prepStmt.setString(1, id);
              prepStmt.executeUpdate();
              prepStmt.close();
         private boolean selectByPrimaryKey(String primaryKey) throws SQLException
              String selectStatement = "select id from ADDRESSES where id = ? ";
              PreparedStatement prepStmt = conn.prepareStatement(selectStatement);
              prepStmt.setString(1, primaryKey);
              ResultSet rs = prepStmt.executeQuery();
              boolean result = rs.next();
              prepStmt.close();
              return result;
         private Collection selectByLastName(String lastname) throws SQLException
              String selectStatement = "select id from ADDRESSES where lastname = ? ";
              PreparedStatement prepStmt = conn.prepareStatement(selectStatement);
              prepStmt.setString(1, lastname);
              ResultSet rs = prepStmt.executeQuery();
              ArrayList a = new ArrayList();
              while(rs.next())
                   String id = rs.getString(1);
                   a.add(id);
              prepStmt.close();
              return a;
         private void loadRow() throws SQLException
              String selectStatement = "select firstname, lastname, address, contactno from ADDRESSES where id = ?";
              PreparedStatement prepStmt = conn.prepareStatement(selectStatement);
              prepStmt.setString(1, this.id);
              ResultSet rs = prepStmt.executeQuery();
              if(rs.next())
                   this.firstname = rs.getString(1);
                   this.lastname = rs.getString(2);
                   this.address = rs.getString(3);
                   this.contactno = rs.getInt(4);
                   prepStmt.close();
              else
                   prepStmt.close();
                   throw new NoSuchEntityException("Row for id " + id + " not found in the dataBase");
         private void storeRow() throws SQLException
              String updateStatement = "update ADDRESSES set firstname = ?, lastname = ?, address = ? contactno = ? where id = ?";
              PreparedStatement prepStmt = conn.prepareStatement(updateStatement);
              prepStmt.setString(1, firstname);
              prepStmt.setString(2, lastname);
              prepStmt.setString(3, address);
              prepStmt.setInt(4, contactno);
              prepStmt.setString(5, id);
              int rowCount = prepStmt.executeUpdate();
              prepStmt.close();
              if(rowCount == 0)
                   throw new EJBException("Storing row for id " + id + " failed.");
    }

    EJB questions should be posted in the EJB forum! :=)
    I did find the compiler message a bit strange. Usually if I don't have a class defined it complains that it cannot find package_name.class_name (when I'm using packages for my own code).

Maybe you are looking for

  • IPod, Apple Universal Dock and Remote

    Hello everyone, So I have this 3-years-old 3g iPod, a 4th generation that still has black and white display and no video. Yesterday I just bought this Apple Universal Dock on a discount which has an IR receiver, audio output but no s-video output (i

  • I have a extensive recipe database in Appleworks 6. Is there a way to convert this to Numbers or Pages?

    New Macbook Pro running Mavericks; Pages; Numbers but no more Appleworks supported. I have a collection of family recipes done in Appleworks 6 [database]--600 recipes+ I can sort on many different fields and easily search the data. I am inserting a s

  • Get my WAN IP

    I am behind a NAT router so if I ask java my IP adress I get my LAN ip, something like 192.168.... But in my Java app I need my internet/WAN IP, which is the IP of the router on the WAN side. I specifically told the router to The ip I get on www.what

  • Creating Interactive Foms

    Hi Everyone! I'm trying to make an interactive form through Dreamweaver 8 which my customers could use to register for the services on my website. The form is quite comprehensive and I therefore think it would be a good idea to divide it on more than

  • How to print online C4700

    How can i change "print offline" to print "online" for hp photosmart c4750? Talk to me like I'm a 6th grader. Or perhaps you can tell by my question.  thanks This question was solved. View Solution.