Sample Program -Restaurant

Sample Program Restaurant

To demonstrate the use of entity beans in applications, you will work on the restaurant application that you built over the past two days. In the restaurant application you built the waiter and chef as stateful and stateless session beans based on how they will be used from a business perspective. Just to recap the work flow of the restaurant application, the customer selects a menu item and places the order. The waiter serves the customer. The waiter bean in turn delegates the order processing to the chef bean. In order to process the order and cook the ordered item, the chef needs to look up the processing details for the ordered item, including its ingredients, serving size, and so on, from the database. Previously, the chef bean prepared the CookedItemImpl object by hard-coding the required data (serving size, ingredients, and so on) for the cooked item.

In today's sample program, you will develop the ItemBean entity bean to retrieve the cooked item data (ingredients, and so on) from the ITEM table in the database. The first step in developing the entity bean is to define the ITEM table structure. The ITEM table is composed of the columns shown in Table 12.1.

Table 12.1. ITEM Table

Column Name

Column Data Type

item_id

NUMBER

item_description

VARCHAR2(30)

item_taste

VARCHAR2(20)

item_temperature

VARCHAR2(20)

item_ingredients

VARCHAR2(200)

item_serving_size

VARCHAR2(30)

Create this database table in the PointBase database using the following SQL command:

 create table item(item_id NUMBER, item_desc VARCHAR2(30), item_taste          VARCHAR2(20), item_temperature VARCHAR2(20), item_ingredients VARCHAR2(200), item_serving_size VARCHAR2(30)); 

After creating the table in the PointBase database, populate the table with data using the following set of SQL commands:

 insert into item values(1, 'Apple Pie','Sweet','Hot', 'Apple, Sugar,          All Purpose Flour, Eggs, Butter','Standard'); insert into item values(2, 'Banana Split Icecream','Sweet','Cold', 'Milk, Sugar,         All Purpose Flour, Eggs, Cream, Bananas','One Scoop'); insert into item values(3, 'Cheese Pizza','Salty','Hot', 'All Purpose Flour,         Cheese, Jalapenos, Tomatoes, Bell Peppers, Olives, Salt','Standard'); insert into item values(4, 'Curly Fries','Salty','Hot', 'Low Cholesterol Oil,         Potatoes cut, Salt','Standard'); insert into item values(5, 'Delhi Kababs','Spicy','Hot', 'Onions, Coriander powder,         Poppy Seeds, Ginger, Salad Oil, Salt, Garlic, Spices, Red Chillies,         Chicken, Yogurt','10 pieces'); insert into item values(6, 'Fresh Pineapple Cake','Sweet','Room Temperature',         'Pineapple, Sugar, All Purpose Flour, Eggs, Butter','1 Slice'); insert into item values(7, 'French Fries - Tub','Salty','Hot',         'Low Cholesterol Oil, Potatoes cut, Salt','Large'); insert into item values(8, 'Hot Dog','Salty','Hot', 'Hot Dog Buns, Meat,         Bread Crumbs, Oatmeal flour, Little Egg White, Spices - Onion, garlic,         salt, pepper etc','Standard'); insert into item values(9, 'Hamburger','Salty','Hot', 'Hamburger, Lettuce,         Onions,Tabasco sauce, Cheddar cheese, Kaiser style buns, Pam Cooking         Spray, Worcestershire sauce','Standard'); 

To verify that the data has been populated in the ITEM table, execute the following SQL command:

 SELECT * FROM ITEM;  

Entity Bean Components

The next step is to design the different components of the entity bean. Refer to the class diagram in Figure 12.6 to understand the different components of the ItemBean entity bean.

Figure 12.6. Class Diagram of the entity bean classes and interfaces for the restaurant application.

graphics/12fig06.gif

The ItemBean bean is composed of the following classes and interfaces:

  • ItemInterface The remote interface of the item entity bean. The services offered by the item bean and used by the chef bean are defined as methods in the ItemInterface remote interface.

  • ItemHome The home interface for creating item entity beans. The ChefBean bean will use the methods in the ItemHome home interface to obtain the references of the ItemBean entity bean. Primarily, the ChefBean bean will use the ItemHome home interface to query the database and obtain ItemBean objects populated with the data from the database based on certain search criteria. When querying, the ChefBean bean will use the finder methods defined in the ItemHome home interface. The ItemHome object will be registered in the naming service of the WebLogic Server. The ChefBean bean acts as an EJB client to retrieve the reference of the ItemHome from the naming service using the JNDI API.

  • ItemBean The actual entity bean implementation class. The ItemBean bean class will implement the EJB callback methods such as ejbCreate(), ejbPostCreate(), ejbActivate(), ejbPassivate(), ejbLoad(), ejbStore(), and so on. Other than this, the service methods of the item entity bean that have been defined in the ItemInterface will be implemented in this class.

  • ItemPK Represents the primary key of the item table. In this case, the item ID in the database is a NUMBER data type and is mapped to an int primitive data type.

The rest of the restaurant application will remain the same, except for the changes made to the cookItem() method of the ChefBean bean class that added the methods for interacting with the ItemBean entity bean.

Source Code

Now take a look at the source code for these classes and interfaces. First, take a look at the source code for the classes and interfaces of the item entity bean. Listing 12.1 shows the source code for the ItemInterface interface.

Listing 12.1 ItemInterface.java
 /******************************************************************************   * Class Name   : ItemInterface.java   * Description  : Remote Interface for Item class. Defines the methods that   *                can be performed by the Item class.   * @author Mandar S. Chitnis, Pravin S. Tiwari, Lakshmi AM       @version 1.1   * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.ejb.cmp; import java.rmi.RemoteException; import javax.ejb.EJBObject; import java.util.*; public interface ItemInterface extends EJBObject{        public int getItemId() throws RemoteException;        public void setItemId(int itemId) throws RemoteException;        public String getItemDesc() throws RemoteException;        public void setItemDesc(String itemName) throws RemoteException;        public String getItemIngredients() throws RemoteException;        public void setItemIngredients(String ingredients)                throws RemoteException;        public String getItemTemperature() throws RemoteException;        public void setItemTemperature(String temperature)                throws RemoteException;        public String getItemTaste() throws RemoteException;        public void setItemTaste(String taste) throws RemoteException;        public String getItemServingSize() throws RemoteException;        public void setItemServingSize(String servingSize)                throws RemoteException; } 

As discussed earlier, the services offered by the item entity bean are declared in the ItemInterface interface. Depending on the implementation, this interface can be either remote or local. For remote interfaces, the ItemInterface interface extends EJBObject. For local interfaces, the ItemInterface interface extends EJBLocalObject. The different services provided by the item are encapsulated in the get/set methods getItemId()/ setItemId(), getItemDesc()/setItemDesc(),getItemIngredients()/setItemIngredients(), getItemTemperature()/setItemTemperature(), getItemTaste()/setItemTaste(),and getItemServingSize()/setItemServingSize(). All of these methods will throw the java.rmi.RemoteException because you are designing the entity bean to be accessed remotely. If you design your entity bean to be accessed locally, the methods in the interface will throw the javax.ejb.EJBException. Take a look at Listing 12.2 for the source code of the ItemHome interface.

Listing 12.2 ItemHome.java
 /******************************************************************************   * Class Name   : ItemHome.java   * Description  : Home Interface for Item class. Defines the methods that can be   *                performed by the Item class.   * @author Mandar S. Chitnis, Pravin S. Tiwari, Lakshmi AM       @version 1.1   * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.ejb.cmp; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; import javax.ejb.FinderException; /**  * This is the home interface for the ItemBean.java.  * In WebLogic, this is implemented by the code-generated container  * class ItemBeanC. A home interface may support one or more create  * methods, which must correspond to methods named "ejbCreate" in the EJBean.  *  */ public interface ItemHome extends EJBHome {   /**    * Corresponding to the ejbCreate method in the ItemBean.java.    *    * @return                  ItemInterface    * @exception               RemoteException    * @exception               CreateException    */   ItemInterface create(int itemId, String temperature, String taste,           String ingredients, String servingSize)throws CreateException,           RemoteException;   /**    * Given a Primary Key, refreshes the EJBean from    * the persistent storage.    *    * @param primaryKey        Primary Key    * @return                  ItemInterface    * @exception               javax.ejb.FinderException    *                          if there is an error finding the bean    * @exception               java.rmi.RemoteException if there is    *                          a communications or systems failure    */   public ItemInterface findByPrimaryKey(ItemPK primaryKey)     throws FinderException, RemoteException;   public ItemInterface findIngredientsByItemName(String itemName)          throws FinderException, RemoteException; } 

The ItemHome interface enables the ChefBean class (the entity bean client in this case) to obtain a handle to the ItemBean entity bean. The create() method defined in the ItemHome interface takes the parameters required to initialize the entity bean and returns an object of the type ItemInterface which is the remote (or local) object reference. The ItemHome interface extends the javax.ejb.EJBHome interface. The create() method throws the javax.ejb.CreateException and java.rmi.RemoteException (for remote interfaces only) exceptions when an error occurs while creating the ItemInterface remote object. You can also write overloaded create() methods as other create() methods with the prefix create in the method name.

After this you will build the actual bean implementation class, that is, the ItemBean. See Listing 12.3.

Listing 12.3 ItemBean.java
 /******************************************************************************   * Class Name   : ItemBean.java   * Description  : Bean Class for Item Bean. Implements the methods that can be   *                performed by the Item Bean.   * @author Mandar S. Chitnis, Pravin S. Tiwari, Lakshmi AM       @version 1.1   * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.ejb.cmp; import java.io.Serializable; import java.util.Enumeration; import java.util.Vector; import javax.ejb.CreateException; import javax.ejb.DuplicateKeyException; import javax.ejb.EJBException; import javax.ejb.EntityBean; import javax.ejb.EntityContext; import javax.ejb.FinderException; import javax.ejb.NoSuchEntityException; import javax.ejb.ObjectNotFoundException; import javax.ejb.RemoveException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; abstract public class ItemBean implements EntityBean {     private EntityContext ctx;        public void setEntityContext(EntityContext ctx) {               System.out.println("setEntityContext called ");               this.ctx = ctx;        }        public void unsetEntityContext() {               System.out.println("ItemBean.unsetEntityContext");               this.ctx = null;        } //abstract get and set methods necessary for all container managed fields     abstract public int getItemId();     abstract public void setItemId(int itemId);        abstract public String getItemDesc();     abstract public void setItemDesc(String itemDesc);     abstract public String getItemIngredients();     abstract public void setItemIngredients(String ingredients);        abstract public String getItemTemperature();        abstract public void setItemTemperature(String temperature);        abstract public String getItemTaste();        abstract public void setItemTaste(String taste);        abstract public String getItemServingSize();        abstract public void setItemServingSize(String servingSize);   /**    * This method is required by the EJB Specification,    * but is not used by this example.    *    */   public void ejbActivate() {       System.out.println("ItemBean.ejbActivate");   }   /**    * This method is required by the EJB Specification,    * but is not used by this example.    *    */   public void ejbPassivate() {     System.out.println("ItemBean.ejbPassivate");   }   /**    * This method is required by the EJB Specification,    * but is not used by this example.    *    */   public void ejbLoad() {     System.out.println("ItemBean.ejbLoad");   }   /**    * Sets the EJBean's modified flag to false.    * set to false to "reset" the variable for the next transaction.    *    */   public void ejbStore() {     System.out.println("ItemBean.ejbStore");   }   /**    * This method is required by the EJB Specification,    * but is not used by this example.    *    * @exception               javax.ejb.RemoveException    *                          if the EJBean does not allow removing the EJBean    */   public void ejbRemove()     throws RemoveException   {     System.out.println("ItemBean.ejbRemove ");   }   /**    * This method corresponds to the create method in the home interface    * "ItemHome.java".    * The parameter sets of the two methods are identical.  When the client calls    * <code>ItemHome.create()</code>, the container (which in WebLogic EJB is    * also the home) allocates an instance of this EJBean and    * calls <code>ItemHome.ejbCreate()</code>.    * <p>    * For container-managed persistence, <code>ejbCreate()</code> returns    * a null, unlike the case of bean-managed    * persistence, where it returns a primary key.    *    * @param itemId                            int itemId,    * @param temperature                     String temperature    * @param taste                         String taste    * @param ingredients         String ingredients    * @param servingSize                     String servingSize    * @exception               javax.ejb.CreateException    *                          if there is a problem creating the bean    */   public ItemPK ejbCreate(int itemId, String temperature, String taste,           String ingredients, String servingSize)     throws CreateException   {     System.out.println("ItemBean.ejbCreate( id = " +             System.identityHashCode(this) +                             ", PK = " +                             itemId + ", " + ", temperature = " +                                     temperature + ",taste = "+taste+",                                     ingredients="+ingredients+", serving size"                                     +servingSize+")");     setItemId(itemId);     setItemTemperature(temperature);     setItemTaste(taste);        setItemIngredients(ingredients);        setItemServingSize(servingSize);     return null;  // See 9.4.2 of the EJB 1.1 specification   }   /**    * This method is required by the EJB Specification,    * but is not used by this example.    *    * @param itemId                            int itemId,    * @param temperature                     String temperature    * @param taste                         String taste    * @param ingredients         String ingredients    */   public void ejbPostCreate(int itemId, String temperature, String taste,           String ingredients, String servingSize)   {     System.out.println("ItemBean.ejbPostCreate (" + itemId() + ")");   }   /**    * Returns the Primary Key identifying this EJBean.    *    * @return                  int itemId    */   private String itemId() {     return "" + System.identityHashCode(this) + ", PK = " +       (String) ((ctx == null) ? "nullctx"                  : ((ctx.getPrimaryKey() == null ?                    "null" : ctx.getPrimaryKey().toString())));   } } 

The ItemBean bean class is the heart of the entity bean and contains all the templates for the functionality associated with the item. Because the ItemBean is an entity bean, it implements the javax.ejb.EntityBean as a part of its adherence to the "component contract" EJB design contract. The life-cycle callback methods of an entity bean such as setSessionContext(), ejbCreate(), ejbPostCreate(), ejbRemove(), ejbActivate(), ejbPassivate(), ejbLoad(), and ejbStore() are implemented by this class (actually the class generated by WebLogic Server's tools!). The primary difference in an entity bean using CMP with the rest of the EJBs is that the bean implementation class of the entity bean that uses CMP is always defined as abstract. The tools provided by the WebLogic Server normally extend this abstract bean implementation class and the required persistence functionality. The EJB container will invoke these methods at different stages in the ItemBean bean's life cycle. In addition to these methods, the ItemBean provides the functionality for the service methods defined in the ItemInterface interface. The methods findByPrimaryKey(), getItemServingSize(), getItemTaste(), and so on, are invoked by the ChefBean, which is the client of the entity bean.

Take a quick look at the cookItem() method where the major part of the action takes place:

 /**     * This method is called by the waiter to cook the item.    *    * @param orderedItem       MenuItem object ordered item    * @return                  object CookedItem    */        public CookedItemImpl cookItem(MenuItem orderedItem){               ItemHome home;               ItemPK orderedItemPk;               String EJBQLIngredients;               String orderedItemName;               String orderedItemServingSize;               String orderedItemTaste;               String orderedItemIngredients;               String orderedItemTemperature;               webLogicLog("cook Item called");               int orderedItemId = orderedItem.getItemId();               CookedItemImpl preparedItem = new CookedItemImpl();               System.out.println("The ordered item desc is:"                       +orderedItem.getItemDesc());               //call the entity bean now to get the attributes               //for the cooked Item.               try{                      home = lookupHome();                      orderedItemPk = new ItemPK(orderedItemId);                      ItemInterface orderedItemInterface =                              (ItemInterface)home.findByPrimaryKey                              (orderedItemPk);                      orderedItemName = orderedItem.getItemDesc();                      preparedItem.setItemName(orderedItemName);                      orderedItemServingSize =                              orderedItemInterface.getItemServingSize();                      preparedItem.setServingSize(orderedItemServingSize);                      orderedItemTaste = orderedItemInterface.getItemTaste();                      preparedItem.setTaste(orderedItemTaste);                      orderedItemIngredients =                              orderedItemInterface.getItemIngredients();                      preparedItem.setIngredients(orderedItemIngredients);                      orderedItemTemperature =                              orderedItemInterface.getItemTemperature();                      preparedItem.setTemperature(orderedItemTemperature);                      System.out.println                              ("Demonstration of findIngredientsByItemName:");                      ItemInterface demonstrateEJBQL =                              (ItemInterface)home.findIngredientsByItemName                              (orderedItemName);                      EJBQLIngredients = demonstrateEJBQL.getItemIngredients();                      System.out.println("Item ingredients obtained :");                      System.out.println();               }               catch(Exception e){                      e.printStackTrace();               }               return preparedItem;        }//end of cookItem 

Previously, in the cookItem() method, the ChefBean created a CookedItemImpl object with the values for ingredients, serving size, and so on, hard-coded. In today's sample program, you will be using an entity bean to retrieve this data from the item table in the database. The cookItem() method does a lookup for the ItemHome object. The actual lookup code is encapsulated in the lookupHome() method of the ChefBean class. After obtaining the ItemHome object reference, the ChefBean obtains the item ID of the ordered item and searches for its data in the database by invoking the findByPrimaryKey() finder method. The finder method returns the ItemHomeInterface object, which is essentially a handle to the remote ItemBean bean implementation object. The ChefBean now invokes the getItemDesc()/setItemDesc(), getItemIngredients()/setItemIngredients(), and similar methods of the ItemInterface, which represent the business methods of the ItemBean entity bean. In the sample application, you will be only retrieving the data from the database using the entity bean.

Finally, Listing 12.4 shows the source code for the ItemPK primary key class.

Listing 12.4 ItemPK.java
 package com.sams.learnweblogic7.ejb.cmp; import java.io.Serializable; public class ItemPK implements Serializable {        public int itemId;        public ItemPK(){               this.itemId = 1;        }        public ItemPK(int itemId){               this.itemId = itemId;        }        public int hashCode(){               return itemId;        }        public boolean equals(Object that){               if(!(that instanceof ItemPK)){                      return false;               }               ItemPK tmp = (ItemPK)that;               return (this.itemId == tmp.itemId);        } } 

From the preceding code, you can see that the ItemPK primary class wraps the primary key data itemId because the ItemBean entity bean represents the data in the database and includes any constraints existing in the database.

Deploy the Program

For EJBs, you need to define the deployment information before compiling the source files of the different beans involved. Moreover, because your entity bean uses CMP, deployment assumes a significant role in the development process. To define the mapping between the fields of the entity bean and the database tables, the preferred way is to use the tools provided by the WebLogic Server. But for this sample application, you will be hand-coding the deployment descriptor files in order to gain an understanding of the different tags involved. You will learn how to use the tool provided by the WebLogic Server for CMP activities during Day 19, "Using WebLogic Tools." The three deployment descriptor files involved in the deployment of the entity bean are ejb-jar.xml, weblogic-cmp-rdbms-jar.xml, and weblogic-jar.xml. Now take a look at what infor mation goes in which deployment descriptor file. The first file that you will study is the ejb-jar.xml file:

 <?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>   <session> ... information about the session beans     </session>     <entity>       <ejb-name>ContainerManagedEntityBean</ejb-name>       <home>com.sams.learnweblogic7.ejb.cmp.ItemHome</home>       <remote>com.sams.learnweblogic7.ejb.cmp.ItemInterface</remote>       <ejb-class>com.sams.learnweblogic7.ejb.cmp.ItemBean</ejb-class>       <persistence-type>Container</persistence-type>       <prim-key-class>com.sams.learnweblogic7.ejb.cmp.ItemPK</prim-key-class>       <reentrant>False</reentrant>       <cmp-version>2.x</cmp-version>       <abstract-schema-name>Item</abstract-schema-name>       <cmp-field>         <field-name>itemId</field-name>       </cmp-field>       <cmp-field>         <field-name>itemDesc</field-name>       </cmp-field>       <cmp-field>         <field-name>itemTaste</field-name>       </cmp-field>       <cmp-field>         <field-name>itemTemperature</field-name>       </cmp-field>       <cmp-field>         <field-name>itemIngredients</field-name>       </cmp-field>       <cmp-field>         <field-name>itemServingSize</field-name>       </cmp-field>       <query>         <query-method>           <method-name>findIngredientsByItemName</method-name>           <method-params>             <method-param>java.lang.String</method-param>           </method-params>         </query-method>         <ejb-ql>           <![CDATA[SELECT OBJECT(a) FROM Item AS a WHERE a.itemDesc = ?1]]>         </ejb-ql>       </query>     </entity>   </enterprise-beans>   <assembly-descriptor>     <container-transaction>       <method>         <ejb-name>Stateless_Session_EJB</ejb-name>        <method-name>*</method-name>       </method>       <method>         <ejb-name>Stateful_Session_EJB</ejb-name>        <method-name>*</method-name>       </method>       <method>         <ejb-name>ContainerManagedEntityBean</ejb-name>        <method-name>*</method-name>       </method>       <trans-attribute>Required</trans-attribute>     </container-transaction>   </assembly-descriptor> </ejb-jar> 

The important tags to be concerned with in the ejb-jar.xml file are:

  • <entity> The entire deployment information of the entity bean is registered between the <entity></entity> tags. Within this tag you will register the logical name of your entity bean as ContainerManagedEntityBean and its home, remote, bean implementation, primary key classes, and interfaces.

  • <persistence-type> The <persistence-type> tag defines the method of persistence followed by the entity bean; whether container for CMP or bean for BMP.

  • <prim-key-class> The <prim-key-class> is used to register the primary key class for the entity bean. For your sample program this will be ItemPK.

  • <cmp-version> The version to be used for performing CMP is defined in the <cmp-version> tag. Because you are using the improved version of CMP, this value should be 2.0.

  • <abstract-schema-name> The logical name of the schema that the entity bean represents is defined in the <abstract-schema-name> tag. The sample program uses only one table item. That is why you will list the item table in this tag.

  • <cmp-field> and <field-name> The sample program uses only a single table and therefore does not have any relationships. So, your CMP mapping is for fields only and not relationships. The <cmp-field> tag lists the fields of the entity bean that need to be mapped.

  • <query> The <query-tag> encapsulates the information for the EJB QL query.

  • <query-method> As seen earlier, the finder methods of the entity bean are registered in the <query-method> tag.

  • <method-name> The name of the finder method of a query is listed in the <method-name> tag.

  • <method-params> and <method-param> The different parameters of the finder method are also registered in the deployment descriptor file using the <method-params> and <method-param> tags as discussed previously.

  • <ejb-ql> Finally, the actual EJB QL query is listed within the <ejb-ql></ejb-ql> tags as you learned earlier.

After this, you will take a look at the entries in the weblogic-cmp-rdbms-jar.xml deployment file. The weblogic-cmp-rdbms-jar.xml file contains settings specific to the WebLogic Server for CMP:

 <!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-rdbms20-persistence-600.dtd'> <weblogic-rdbms-jar>   <weblogic-rdbms-bean>     <ejb-name>ContainerManagedEntityBean</ejb-name>     <data-source-name>ejb-datasource-learnweblogic7</data-source-name>     <table-name>item</table-name>     <field-map>       <cmp-field>itemId</cmp-field>       <dbms-column>item_id</dbms-column>     </field-map>     <field-map>       <cmp-field>itemDesc</cmp-field>       <dbms-column>item_desc</dbms-column>     </field-map>     <field-map>       <cmp-field>itemIngredients</cmp-field>       <dbms-column>item_ingredients</dbms-column>     </field-map>     <field-map>       <cmp-field>itemTemperature</cmp-field>       <dbms-column>item_temperature</dbms-column>     </field-map>     <field-map>       <cmp-field>itemServingSize</cmp-field>       <dbms-column>item_serving_size</dbms-column>     </field-map>     <field-map>       <cmp-field>itemTaste</cmp-field>       <dbms-column>item_taste</dbms-column>     </field-map>    </weblogic-rdbms-bean>   <create-default-dbms-tables>True</create-default-dbms-tables> </weblogic-rdbms-jar> 

The important entries that you need to be aware of in the weblogic-cmp-rdbms-jar.xml file are listed here:

  • <ejb-name> The <ejb-name> tag signifies the name of the entity bean whose information is registered in this file.

  • <data-source-name> The information about the database connection pool or data source that the entity bean requires to connect to is listed in the <data-source-name> tag. For your sample program this is ejb-data-source-learnweblogic7.

  • <table-name> The <table-name> lists the physical database table that the entity bean maps to. In this case it is the item table.

  • <field-map> The <field-map> tag encloses the mapping information between the entity bean field and the database column.

  • <cmp-field> The entity bean's field that requires container-management is listed in the <cmp-field> tag.

  • <dbms-column> The database column to which the <cmp-field> maps to is listed in the <dbms-column> tag.

The final deployment descriptor file that you need to make changes to is the weblogic-ejb-jar.xml file. This file contains the deployment information for all the EJBs deployed in the WebLogic Server such as session, entity, or message-driven beans:

 <?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>Stateless_Session_EJB</ejb-name>     <jndi-name>Chef_Home</jndi-name>   </weblogic-enterprise-bean>   <weblogic-enterprise-bean>     <ejb-name>Stateful_Session_EJB</ejb-name>     <jndi-name>Waiter_Home</jndi-name>   </weblogic-enterprise-bean>   <weblogic-enterprise-bean>     <ejb-name>ContainerManagedEntityBean</ejb-name>     <entity-descriptor>       <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>CMP_ItemHome</jndi-name>   </weblogic-enterprise-bean> </weblogic-ejb-jar> 

The file lists the other session beans of the restaurant application apart from the ContainerManagedEntityBean bean (which is the entity bean that you developed). The rest of the information, such as the JNDI name for the bean's home interface, is also listed here.

Whew! You modified a lot of files there! No wonder WebLogic Server provides tools for CMP. Now that you have a hands-on understanding of deploying the entity bean, take a look at the next step: compiling the program.

Compile the Program

Use the compile.bat batch file provided to compile the classes and interfaces of the restaurant application. This includes the ItemBean entity bean classes, the customer EJB client, and the supporting Java classes. The batch file compiles the files of the restaurant application located in the

 C:\book\code\EJB\CMP\src\*.java  

directory. The contents of the compile.bat batch file are given here:

 call C:\bea\user_domains\mydomain\setEnv  set CLASSPATH=%CLASSPATH%;C:\book\code\EJB\CMP\Client\fscontext.jar; cd C:\book\code\EJB\CMP\deploy del META-INF rmdir META-INF mkdir META-INF copy C:\book\code\EJB\CMP\src\*.xml META-INF del C:\book\code\EJB\CMP\src\*.bak javac -d C:\book\code\EJB\CMP\deploy C:\book\code\EJB\CMP\src\*.java jar cvf CMP.jar META-INF/ com\sams\learnweblogic7\ejb\cmp\*.class copy CMP.jar C:\book\code\EJB\CMP\deploy\deploy_jars cd deploy_jars java weblogic.ejbc -keepgenerated CMP.jar EJBCMPDeploy.jar pause cd C:\bea\user_domains\mydomain 

Use the same steps and command that you used to compile the source files for session beans. From the preceding listing, the command given is:

 javac -d C:\book\code\EJB\CMP\deploy C:\bok\code\EJB\CMP\src\*.java  

After successfully compiling the source files, use the following command to create a Java archive of the files.

 jar cvf CMP.jar META-INF/ com\sams\learnweblogic7\ejb\cmp\*.class  

The final step in the compilation process is to generate the stubs and skeletons for the remote interface of the entity bean and the other EJBs.

 java weblogic.ejbc -keepgenerated CMP.jar EJBCMPDeploy.jar  

Now you are all set to execute the sample program.

Execute the Program

Because there are two parts to the restaurant application, the server side as well as the client side, you will execute both of them and see their output on the screen.

After deploying the stateful session bean WaiterBean in the previous step (using any of the three methods that you discussed earlier), you need to start up the WebLogic Server using the batch file startWebLogic.bat. This step causes the EJB container in the WebLogic Server to initialize the deployed WaiterBean bean and keep its home interface WaiterHome registered with the WebLogic Server's naming service.

Now, open up another command prompt window and execute the EJB client class Customer as a stand-alone Java application. Upon executing the Customer class, you'll see the following output in the command prompt window of the Customer class, as shown in Figure 12.7.

Figure 12.7. Screen shot showing the output in the command prompt window of the Customer class.

graphics/12fig07.jpg

As the work flow of actions between the customer, waiter, chef, and ItemBean beans progresses, the ItemBean generates output on the console of the WebLogic Server. This output is shown in Figure 12.8.

Figure 12.8. Screen shot showing the output of the ItemBean in the command prompt window of the WebLogic Server console.

graphics/12fig08.jpg



Sams Teach Yourself BEA WebLogic Server 7. 0 in 21 Days
Sams Teach Yourself BEA WebLogic Server 7.0 in 21 Days
ISBN: 0672324334
EAN: 2147483647
Year: 2002
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net