Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Enhancing the CMP Implementation

Adding More Use-Case Pathways

In Chapter 11 we demonstrated the ability to inquire about a Customer object, as well as to insert, update, and delete one. However, the Maintain Relationships use-case has quite a few more pathways. These relate to adding, updating, and deleting roles and addresses for that customer. The next section covers those changes.

In the CMP implementation we have no DAO classes, and we have already seen most of the CMP beans in action. However, we will present other changes that are required of these beans later in this chapter. Obviously we can't use the DOS-based client presented in the preceding section; it was just a means to test the EJB implementation of our three entity beans. This client was really playing the role that our use-case controller needs to play. We saw the use-case controller in action in Chapter 11. However, it will need a few changes.

We will also require some additions to the JSP rltnInquiry.jsp to be able to handle the display of multiple role/address combinations for a customer. The last changes we need to make are to the servlet, and these changes are meant only to support how we instantiate the controller. Let's start at the front this time with the changes necessary for the JSP side of Remulak.

Changes to the JSPs

The JSPs presented earlier require just a few changes. Actually, the only JSP that must be modified is rltnInquiry.jsp, and we have to add a new JSP, rltnAddress.jsp. In Chapter 11, the JSP for displaying a Customer object was rather straightforward. Now, however, we have to deal with a CustomerValue object having not only Customer information but also Role and Address information. In addition, the CustomerValue object was created in CustomerDAO in the non-EJB solution. The whole DAO layer is gone with CMP. We will have to make the bean do this for us now. Before we dive into the JSP, we should review how CustomerValue is created because this will make the additions to rltnInquiry.jsp more straightforward.

In CustomerBean, the result of the findByCustomerNumber() method, which we saw previously in the home interface, causes a Customer Bean object to be created for us. To get the proxy image of this bean, we will invoke its getCustomerValue() operation. We will see this in action a bit later. For now let's explore the getCustomerValue() operation in CustomerBean:

public CustomerValue getCustomerValue()
   throws RemoteException {

   CustomerValue myCustVal = new CustomerValue();

   myCustVal.setCustomerId(getCustomerId());
   myCustVal.setCustomerNumber(getCustomerNumber());
   myCustVal.setFirstName(getFirstName());
   myCustVal.setMiddleInitial(getMiddleInitial());
   myCustVal.setPrefix(getPrefix());
   myCustVal.setSuffix(getSuffix());
   myCustVal.setLastName(getLastName());
   myCustVal.setPhone1(getPhone1());
   myCustVal.setPhone2(getPhone2());
   myCustVal.setEMail(getEMail());

   // Get the RoleValue objects by iterating over the Roles
    collection
   ArrayList returnList = new ArrayList();
   Iterator roleIter = getRoles().iterator();
   if(! roleIter.hasNext()) {
     log(" No roles for this customer");
   }
   else {
      while (roleIter.hasNext()) {
      Role role = (Role) roleIter.next();
      RoleValue roleValue = role.getRoleValue();
      roleValue.setCustomerValue(myCustVal);
      returnList.add(roleValue);
     }
   }
   myCustVal.setRoleValue(returnList);

   return myCustVal;
}

Notice that in addition to setting the base attributes from Customer, getCustomerValue() iterates over the beans contained in the collection of RoleBean objects. Each instance of RoleBean in the ArrayList object is sent a getRoleValue() message. Let's follow the trail to the RoleBean now and look at the getRoleValue() operation within that bean:

public RoleValue getRoleValue()
   throws RemoteException {

   RoleValue myRoleVal = new RoleValue();

   myRoleVal.setRoleId(getRoleId());
   myRoleVal.setRoleName(getRoleName());
   myRoleVal.setAddressValue(getAddress().getAddressValue());

   return myRoleVal;

}

For the RoleBean object in the contained ArrayList within Customer Bean, we are setting the local value as well. The last assignment is then to send a getAddressValue() message to the contained AddressBean reference that exists in the RoleBean object. Let's follow the trail to the AddressBean object and look at its getAddressValue() operation:

public AddressValue getAddressValue()
   {
     AddressValue myAddrVal = new AddressValue();

     myAddrVal.setAddressId(getAddressId());
     myAddrVal.setAddressLine1(getAddressLine1());
     myAddrVal.setAddressLine2(getAddressLine2());
     myAddrVal.setAddressLine3(getAddressLine3());
     myAddrVal.setState(getState());
     myAddrVal.setCity(getCity());
     myAddrVal.setZip(getZip());

     return myAddrVal;
}

The getAddressValue() operation also gets the related Address object's internal values. So to recap, by the getCustomerValue() operation's iteration over its collection of roles, the RoleValue object that now exists in the CustomerValue ArrayList of RoleValue also contains its related AddressValue object.

The reason for these proxy objects is to reduce expensive network trips and to decouple the use of the beans from the beans' states. However, it also raises the question of just how far you should chase the object graph. The graph could consist of all possible relationships to the very bottom leaf. Clearly this would be overkill for someone who wanted only specific information. Much thought has been devoted to this issue; the possibilities range from fully chasing the object graph to initiating a lazy loading strategy. Lazy loading entails only loading the other related objects in the graph on request. Floyd Marinescu, with the Middleware Company (http://www.middleware-company.com), has written some excellent articles on this very topic. His thoughts can be found on the portal he manages at http://www.theserverside.com.

The work that must happen on rltnInquiry.jsp should make a bit more sense. The JSP must not only extract information about the Customer object from CustomerValue, but it also needs to iterate through all the RoleValue objects and the AddressValue object within each RoleValue object. FIGURE 12-15 is the result of the modifications that follow:

<%@ page language="java" contentType="text/html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<jsp:useBean id="custVal" scope="request"
class="com. jacksonreed.CustomerValue" />
<bean:define id="custOther" name="custVal"/>

FIGURE 12-15 A customer with more than one address

The heading of the JSP has changed. The biggest difference is the inclusion of the taglib directives. This is where we will utilize some excellent work by the folks from Apache on the Struts framework. Without Struts and other taglib directives on the market today, JSPs would be bloated with scripting elements. The <bean:define> tag makes a copy of the CustomerValue object for Struts so that it can work its magic. Everything is the same as in Chapter 11, until we reach the next set of comments:

<HTML>
<HEAD>
<TITLE>Remulak Relationship Inquiry</TITLE>
</HEAD>
<BODY >
<form action="rltnUpdate" method="get">
<P><FONT size=6>Remulak Relationship Inquiry</FONT></P>
<table border="1" width="20%" >
   <tr>
     <th align="center">
        Customer Number
     </th>
   </tr>
   <tr>
     <td align="left" bgColor="aqua">
        <%= custVal.getCustomerNumber() %>
     </td>
   </tr>
</table>
<p><p>
<table border="1" width="60%" >
   <tr>
     <th align="center" width="10%">
        Prefix
     </th>
     <th align="center" width="25%">
        First Name
     </th>
     <th align="center" width="2%">
        MI
     </th>
     <th align="center" width="25%">
        Last Name
     </th>
     <th align="center" width="10%">
        Suffix
     </th>
   </tr>
   <tr>
     <td align="left" width="10%" bgColor="aqua">
        <jsp:getProperty name="custVal" property="prefix"/>
     </td>
     <td align="left" width="25%" bgColor="aqua">
        <%= custVal.getFirstName() %>
     </td>
     <td align="left" width="2%" bgColor="aqua">
        <%= custVal.getMiddleInitial() %>
     </td>
     <td align="left" width="25%" bgColor="aqua">
        <%= custVal.getLastName() %>
     </td>
     <td align="left" width="10%" bgColor="aqua">
        <%= custVal.getSuffix() %>
     </td>
   </tr>
</table>
<p><p>
<table border="1" width="60%" >
   <tr>
      <th align="center" width="25%">
         Phone1
      </th>
     <th align="center" width="25%">
        Phone2
     </th>
     <th align="center" width="25%">
        E-Mail
     </th>
   </tr>
   <tr>
      <td align="left" width="25%" bgColor="aqua">
         <%= custVal.getPhone1() %>
      </td>
      <td align="left" width="25%" bgColor="aqua">
         <%= custVal.getPhone2() %>
      </td>
      <td align="left" width="25%" bgColor="aqua">
         <%= custVal.getEMail() %>
      </td>
    </tr>
</table>
<!--Buttons for Customer -->
<table border="0" width="30%" >
   <tr>
     <th align="left" width="33%">
        <INPUT type=submit value="Edit Customer" name=action >
     </th>
     <th align="left" width="33%">
        <INPUT type=submit value="Delete Customer" name=action >
     </th>
     <th align="left" width="33%">
        <INPUT type=submit value="Add Address" name=action>
     </th>
   </tr>
</table>

In the next block of code notice the <logic:iterate> tag. This is one of the features offered by Struts through its logic taglib. The name parameter points to the copy of the CustomerValue bean. The property parameter points to the RoleValue ArrayList that is sitting in CustomerValue.

<!--This is the Struts iterator that will cycle over our
RoleValue -->
<logic:iterate id="role" name="custOther" property="roleValue">
<!--Role Name -->
<hr>
<table border="1" width="20%" >
   <tr>
     <th align="center">
        Role Name
     </th>
   </tr>
   <tr>
     <td align="left" bgColor="aqua">
        <bean:write name="role" property="roleName"
           filter="true"/>

The <bean:write> tag points to the getRoleName() operation in the RoleValue object. Notice that we don't have to reference the actual accessor, just the property. This reference causes the accessor's value to be displayed.

In the code that follows, the <bean:write> tag is performing the same function as described with roleName; however, note how Struts makes the syntax so much easier to write than scripting does. The statement property="addressValue.addressLine1" inside the tag is the equivalent of writing GetAddressValue().getAddressLine1() in a scripting element.

     </td>
   </tr>
</table>
<!--Address Lines -->
<table border="1" width="60%" >
   <tr>
     <th align="center" width="10%">
        Address
     </th>
   </tr>
   <tr>
     <td align="left" width="60%" bgColor="aqua">
        <bean:write name="role" property="addressValue.
         addressLine1" filter="true"/>
        <br>
        <bean:write name="role" property="addressValue.
         addressLine2" filter="true"/>
        <br>
        <bean:write name="role" property="addressValue.
         addressLine3" filter="true"/>
     </td>

The following snippet of code shows the placement of the remaining attribute elements of the AddressValue object:

   </tr>
</table>
<!--City, State, ZIP -->
<table border="1" width="60%" >
   <tr>
     <th align="center" width="25%">
        City
     </th>
     <th align="center" width="25%">
        State
     </th>
     <th align="center" width="25%">
        Zip
     </th>
   </tr>
   <tr>
     <td align="left" width="25%" bgColor="aqua">
        <bean:write name="role" property="addressValue.city"
         filter="true"/>
     </td>
     <td align="left" width="25%" bgColor="aqua">
       <bean:write name="role" property="addressValue.state"
        filter="true"/>
     </td>
     <td align="left" width="25%" bgColor="aqua">
        <bean:write name="role" property="addressValue.zip"
         filter="true"/>
     </td>
   </tr>
</table>

The next portion of code in the JSP associates a hyperlink with the buttons that display beneath the address (Edit and Delete), as shown in FIGURE 12-15. We can't simply create a button with an <INPUT> tag because we have to customize the query string when the button is pushed. This is necessary because if someone wants to edit the second of three role/address elements on the form, you must indicate to the servlet which ones they want to change.

<!--Buttons for Address -->
<table border="0" width="30%" >
   <tr>
     <th align="left" width="33%">
        <a href="rltnUpdate?action=Edit+Address&roleId=<bean:
         write name="role" property="roleId" filter="true"/>
         &addressId=<bean:write name="role" property=
         "addressValue.addressId" filter="true"/>
          &customerNumber=<%= custVal.getCustomerNumber()
         %>&customerId=<%= custVal.getCustomerId() %>"><img
         src=images/edit.gif border="0" alt="Update Role or
         Address">
         </a>
     </th>
     <th align="left" width="33%">
        <a href="rltnUpdate?action=Delete+Address&roleId=<bean:
         write name="role" property="roleId" filter="true"/>
         &addressId=<bean:write name="role" property=
         "addressValue.addressId" filter="true"/>
         &customerNumber=<%= custVal.getCustomerNumber()
         %>&customerId=<%= custVal.getCustomerId() %>"><img
          src=images/delete.gif border="0" alt="Delete Role and
          Address">
         </a>
     </th>
     <th align="left" width="33%">
        &nbsp
     </th>
   </tr>
</table>
</logic:iterate>

The tag that signals the end of the iteration, </logic:iterate>, causes the loop to cycle again until there are no more RoleValue objects in the CustomerValue ArrayList.

        <INPUT type="hidden" name="customerNumber" value='<%=
         custVal.getCustomerNumber() %>' >
        <INPUT type="hidden" name="customerId" value='<%= custVal.
         getCustomerId() %>' >
        </form>
        </BODY>
        </HTML>

Many tag libraries are in circulation today. However, the Struts framework, from the Apache Software Foundation at jakarta.apache.org, is both free and quite complete in its implementation. In addition, Struts is constructed with components, so you can use only what you want. As of this writing, Sun is working on formulating a standard tag library that will be made part of a JDK release in the future. It is thought that much of what we see in Struts will end up in that effort. Whatever the case, tag libraries are essential for reduced maintenance and accelerated application development.

Adding an Address JSP

As described already, the client can now view a Customer object and its associated Role and Address objects. The mechanism to pass that information back to the servlet has also been reviewed. Now we need rltnAddress.jsp to allow us to both add and update Role/Address pairs and assign them to a Customer object. FIGURE 12-16 shows what the Address JSP would look like in the browser if the client had depressed the Edit button for the first address related to customer abc1234.

FIGURE 12-16 JSP to add and update addresses

The rltnAddress JSP is straightforward:

<%@ page language="java" contentType="text/html" %>
<jsp:useBean id="addrVal" scope="request"
        class="com.jacksonreed.AddressValue" />
<jsp:useBean id="roleVal" scope="request"
        class="com.jacksonreed.RoleValue" />
<jsp:useBean id="custVal" scope="request"
         class="com.jacksonreed.CustomerValue" />

The heading is a bit different from the heading for the rltnInquiry and rltnCustomer JSPs. There are no Struts tag library references because we aren't using its features on this page. However, because we are addressing elements from both RoleValue and AddressValue, we must reference those items with <jsp:useBean> tags.

In the next example I have once again used a combination of both action elements (<jsp:getProperty>) and scripting elements (<% %>) just to show the variety.

<HTML>
<HEAD>
<TITLE>Remulak Address Add/Update</TITLE>
</HEAD>
<BODY >

<P><FONT size=6>Remulak Address Add/Update For Customer &nbsp
'<%= custVal.getCustomerNumber() %>'
</FONT></P>

<%--Output form with submitted values --%>
<form action="rltnUpdate" method="get">
   <table>
     <tr>
        <td>Role Name:</td>
        <td>
          <input type="text" name="roleName"
           value="<jsp:getProperty name="roleVal"
           property="roleName"/>">
        </td>
     </tr>
     <tr>
        <td>Address Line 1:</td>
        <td>
           <input type="text" name="addressLine1"
           value='<%= addrVal.getAddressLine1() %>' >
        </td>
     </tr>
     <tr>
        <td>Address Line 2:</td>
        <td>
           <input type="text" name="addressLine2"
            value='<%= addrVal.getAddressLine2() %>' >
        </td>
     </tr>
     <tr>
        <td>Address Line 3:</td>
        <td>
           <input type="text" name="addressLine3"
            value='<%= addrVal.getAddressLine3() %>' >
        </td>
      </tr>
      <tr>
        <td>City:</td>
        <td>
           <input type="text" name="city"
            value='<%= addrVal.getCity() %>' >
        </td>
     </tr>
     <tr>
        <td>State:</td>
        <td>
           <input type="text" name="state"
            value='<%= addrVal.getState() %>' >
        </td>
     </tr>
      <tr>
        <td>Zip:</td>
        <td>
           <input type="text" name="zip"
            value='<%= addrVal.getZip() %>' >
        </td>
      </tr>
   </table>
<INPUT type="hidden" name="customerNumber"
value='<%= custVal.getCustomerNumber() %>' >
<INPUT type="hidden" name="customerId"
         value='<%= custVal.getCustomerId() %>' >
<INPUT type="hidden" name="roleId"
         value='<%= roleVal.getRoleId() %>' >
<INPUT type="hidden" name="addressId"
         value='<%= addrVal.getAddressId() %>' >
<INPUT type=submit value="Add/Update Address" name=action>
</form>
</BODY>
</HTML>

Notice that in the hidden fields at the bottom of the page we now have the primary key of all three value objects: customerId, roleId, and addressId.

Changes to the Servlet

To accommodate the enhanced Maintain Relationships use-case support, changes are required to the work that was done in Chapter 11 with regard to both the user interface controller (RemulakServlet) and the use-case controller (UCMaintainRltnshp). The Remulak CustomerBean, AddressBean, and RoleBean objects are working fine as entity EJBs, but as of yet, the only client accessing them is the DOS-based client built to test the deployment. We have the JSPs in place, but now they need something to talk to, and that is our servlet.

The changes necessary to the servlet are quite small—so small, in fact, that I will merely point out the differences. The primary change is how we find the use-case controller. In Chapter 11 the use-case controller was just a JavaBean. The use-case controller in this enhanced architectural prototype will be a stateless session EJB. The only way for a client to talk to the EJB container is to get the home interface of the bean, in this case UCMaintainRltnshpHome. Once the home interface is available to RemulakServlet, the door is wide open for us to work with the container and the beans within. Let's start by examining the changes necessary to one of the servlet operations, doRltnCustomer Inquiry():

private void doRltnCustomerInquiry(HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException, RemoveException,
   CreateException, NamingException, FinderException {
   String customerNumber = request.getParameter
   ("customerNumber");

   if (customerNumber == null) {
       throw new ServletException("Missing customerNumber
       info");
   }

   UCMaintainRltnshpHome home = lookupHome();

   UCMaintainRltnshp UCController =
       (UCMaintainRltnshp) PortableRemoteObject.narrow(home.
       create(), UCMaintainRltnshp.class);

The first difference to point out is how we obtain the reference to UCMaintainRltnshp. A private lookupHome() operation, which we will look at in this section, is called to get a reference to our home interface for UCMaintainRltnshp. The next statement calls create() on the home interface, which returns a reference to the remote interface. Remember that it isn't the bean, but the remote interface, that acts as the proxy to the bean sitting in the container.

// Call to controller method in session bean
CustomerValue custVal =
       UCController.rltnCustomerInquiry(customerNumber);

// Set the custVal object into the servlet context so that
// JSPs can see it
request.setAttribute("custVal", custVal);

// Remove the UCMaintainRltnshp controller
UCController.remove();

// Forward to the JSP page used to display the page
forward("rltnInquiry.jsp", request, response);
   }

The remainder of the servlet is identical to the non-EJB solution. The only other notable difference is how we remove the reference to the controller when the servlet is done with it. In Chapter 11 we set the reference to null. In the case of our session bean, we call remove(). I won't review the other operations in RemulakServlet because the changes to be made are identical. However, let's look at the lookup Home() operation that returns the home interface:

private UCMaintainRltnshpHome lookupHome()
    throws NamingException {

   // Look up the bean's home using JNDI
   Context ctx = getInitialContext();
   try {
    Object home = ctx.lookup("remulak.UCMaintainRltnshpHome");

    return (UCMaintainRltnshpHome) PortableRemoteObject.narrow
             (home, UCMaintainRltnshpHome.class);

    } catch (NamingException ne) {
      logIt("The client was unable to lookup the EJBHome." +
          "Please make sure ");
      logIt("that you have deployed the ejb with the JNDI
      name " + "UCMaintainRltnshpHome" +
             " on the WebLogic server at ");
      throw ne;
   }
}

The lookup starts with getting the Context reference for the container. The getInitialContext() operation returns the necessary string to be used by JNDI to prepare for the home interface lookup. The ctx.lookup() call takes the JNDI name of the UCMaintainRltnshp Home interface and returns a reference:

private Context getInitialContext() throws NamingException {
   try {

     // Get an initial context
     Properties h = new Properties();

     h.put(Context.INITIAL_CONTEXT_FACTORY,
      "weblogic.jndi.WLInitialContextFactory");

     h.put(Context.PROVIDER_URL, url);

     return new InitialContext(h);
   } catch (NamingException ne) {
     logIt("We were unable to get a connection to the " +
       " WebLogic server at ");
     logIt("Please make sure that the server is running.");
     throw ne;
   }
}

The getInitialContext() operation is the only place where differences will be found, because of the unique needs of the EJB container in use. However, this operation is very isolated and could be separated out in a factory class that holds the unique code to return the appropriate Context object.

Changes to the Use-Case Controller

The use-case controller, UCMaintainRltnshp, will require structural changes to accommodate the fact that it is now a session bean. However, the use-case pathway operations will remain intact with the exception of the following changes:

  • Just as with the servlet, the entity beans used by the controller must return a home interface reference before we can work with them.

  • The TransactionContext object and all the unit-of-work management code that wrapped the calls to the beans in the non-EJB solution must be removed. These are no longer necessary because the container will manage the transactions according to the assembly descriptor covered earlier in this chapter.

Let's start by looking at the differences in the structure of the revised UCMaintainRltnshp class:

package com.jacksonreed;

import java.util.Enumeration;
import java.util.Random;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.ejb.EJBException;

import javax.naming.InitialContext;

import javax.rmi.PortableRemoteObject;

import java.rmi.RemoteException;
import javax.naming.NamingException;

import javax.ejb.FinderException;
import javax.ejb.NoSuchEntityException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;

import javax.naming.NamingException;

public class UCMaintainRltnshpBean implements SessionBean {

   private static Random generator;
   private SessionContext sessionContext;

   public void ejbCreate() {
   }
   public void ejbPassivate() {
   }
   public void ejbRemove() {
   }
   public void ejbActivate() {
   }

   public void setSessionContext(SessionContext context) {
     sessionContext = context;
   }

The big visual difference between the controller implemented in Chapter 11 and this one is that we have quite a few more imports to support the EJB world, and we also have skeleton callback methods that we won't use. Notice that the controller implements SessionBean. Some practitioners lobby for creating adapter classes that the bean implements. Doing so allows you to hide all the empty callback operations you don't use and override the ones you need to use. I choose to leave them as they are, empty in the bean. It is clearer to see them there. You also avoid the problem of getting into a multiple inheritance quandary if your bean really does need to subclass another of your entity or session beans.

Next I will present two operations out of the new controller bean to show the differences from the solution laid out in Chapter 11. I think you will find that they are much cleaner because all the transaction logic is removed:

public CustomerValue rltnCustomerInquiry(String
customerNumber)
   throws NamingException, RemoteException, FinderException {

   CustomerHome customerHome;

   customerHome = lookupCustomerHome();

   Customer customer = customerHome.
         findByCustomerNumber(customerNumber);
   return customer.getCustomerValue();
}

Gone is the reference to TransactionContext and the call to its beginTran() and commitTran() operations. We must still look up the CustomerHome interface as we did the CMaintainRltnshpHome inter-face in the servlet. It is a local operation and is identical in intent. The exceptions coming back are defined in the javax.ejb package. They are all considered application-level exceptions. Let's now look at the rltnAddCustomer() operation:

public void rltnAddCustomer(CustomerValue custVal)
    throws NamingException, RemoteException, FinderException {

    // Seed random generator
    seedRandomGenerator();

    CustomerHome customerHome;

    customerHome = lookupCustomerHome();

    // Generate a random integer as the key field
    custVal.setCustomerId(generateRandomKey());

   try {
     Customer myCustomer = customerHome.create(custVal);
   } catch (CreateException ce) {
     throw new EJBException (ce);
   }
}

Gone are all the complicated catch blocks from the prior implementation, as well as the calls to the beginTran(), commitTran(), and rollBackTran() operations within TransactionContext. If the call to create the customer fails, CreateException (an application-level exception) is caught and EJBException (a system-level exception) is thrown. This action will immediately force a rollback by the container for the transaction. Remember that this method was set to RequiresNew by the assembly descriptor.

One more operation from the control class will be of interest because it really demonstrates the efficiency that EJB implementation brings to the architecture. It is the rltnAddAddress() operation:

public void rltnAddAddress(AddressValue addrVal, CustomerValue
custVal, RoleValue roleVal)
   throws NamingException, RemoteException, RemoveException {

   // Seed random generator
   seedRandomGenerator();

   RoleHome roleHome;
   roleHome = lookupRoleHome();
   AddressHome addressHome;
   addressHome = lookupAddressHome();
   CustomerHome customerHome;
   customerHome = lookupCustomerHome();

   // Generate a random integer as the primary-key field or
   // Role
   roleVal.setRoleId(generateRandomKey());

   // Generate a random integer as the primary-key field or
   // Address
   addrVal.setAddressId(generateRandomKey());

   try {
     Customer customer =customerHome.
            findByCustomerId(custVal.getCustomerId());
     Address myAddress = addressHome.create(addrVal);
     Address address = addressHome.
            findByAddressId(addrVal.getAddressId());

     Role myRole = roleHome.create(roleVal, address,
     customer);
 
   } catch (CreateException ce) {
     throw new EJBException (ce);
   } catch (FinderException fe) {
     throw new EJBException (fe);
   }
}

In this operation we are trying to create a new RoleBean object and a new AddressBean object, and then associate the RoleBean object with the CustomerBean object. This is a good example of several invocations to multiple beans; if something isn't found or created properly, we need to roll back. The create() operation for RoleBean takes in both the newly created AddressBean object and the CustomerBean object. When the RoleBean object sets these values in its create() method, CMP will ensure that the foreign keys are taken care of and the database is updated properly.

  • + Share This
  • 🔖 Save To Your Account