Flylib.com

Books Software

 
 
 

Sams Teach Yourself BEA WebLogic Server 7.0 in 21 Days - page 305

Day 11

Quiz

A1:

A stateful session bean maintains a conversational state with an EJB client. This means that until the end of its life cycle, the EJB container maintains an association between a stateful bean and the EJB client that it services. A stateless session bean, on the other hand, does not maintain any state information regarding the EJB client. Hence, the EJB container maintains an instance pool of stateless session beans that can be allocated to service any EJB client.

A2:

The ejbCreate() method is normally overloaded and used to initialize the session bean with different values. Because a stateless session bean does not maintain state with an EJB client, there is no need for it to have any overloaded ejbCreate() methods . The default ejbCreate() method with no parameters is sufficient.

A3:

A stateless session bean does not maintain any state. Hence, the EJB container can allocate any instance of a stateless session bean from the bean instance pool to service EJB clients . A stateful session bean needs to be activated and passivated by the EJB container to free up resources because the bean maintains a conversational state with the EJB client, and hence it has the ejbActivate() and ejbPassivate() callback methods. This is not the case with stateless session beans, and hence they do not need to have the ejbActivate() and ejbPassivate() callback methods.

Exercise

A1:

The code listing below illustrates this RMI client. You will first obtain the InitialContext object using "weblogic.jndi.WLInitialContextFactory" for the Context factory. After obtaining the IntialContext object, you will create the home object for your EJB by doing a lookup for it with its JNDI name and then performing a PortableRemoteObject.narrow() on this class. To test whether the object is properly obtained, you will perform a create on the WaiterHome object. To run the client, open a DOS session and include your EJB deployable file in the CLASSPATH of this session. Then run this Java client:

import java.io.PrintStream; 
import weblogic.utils.Debug;
import javax.naming.*;
import java.util.Hashtable;
import javax.rmi.*;

import com.sams.learnweblogic7.ejb.bmp.*;

public class EJBRMIClient {

  public final static String
          JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
  static String url = "t3://localhost:7001";

  public EJBRMIClient() {}

  public static void main(String[] argv) throws Exception {
    try {
      InitialContext ctx = getInitialContext(url);
      Object home = ctx.lookup("Waiter_Home");
      WaiterHome myWaiterHome =
              (WaiterHome)PortableRemoteObject.narrow(home,
              WaiterHome.class);
      System.out.println(myWaiterHome.create());
    }
    catch (Throwable t) {
      t.printStackTrace();
      System.exit(-1);
    }
   }

  private static InitialContext getInitialContext(String url)
       throws NamingException
  {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    return new InitialContext(env);
  }
}

Day 12

Quiz

A1:

An entity bean can persist data in two ways: using container-managed persistence (CMP) and bean-managed persistence (BMP).

A2:

In CMP the responsibility of writing and implementing the actual persistence functionality lies with the EJB container, more specifically , with the tools provided by the EJB container. All the JDBC code for creating a JDBC connection, creating a statement, executing the statement, retrieving the data from the result set, and so on is generated by the container provider's tools. Moreover, the EJB 2.0 specification provides for an improved and portable CMP solution along with a new query language called EJB QL that overcomes most of the limitations and shortcomings encountered in the EJB 1.1 specification.

A3:

Relationships between entity beans can be one-to-one, one-to-many, and many-to-many. Relationships between entity beans are implemented as get XXX ()/set XXX () methods . Depending on how the traversing from one entity bean to another is required, entity bean relationships can be either unidirectional or bidirectional. The navigational direction of entity bean relationships is defined in the deployment descriptor file.

A4:

Entity bean fields can be defined as container-managed persistent, that is, CMP fields, or as container-managed relationship, or CMR, fields. The definition of these fields is listed in the deployment descriptor file based on what the fields represent in an entity bean.

A5:

Dependent objects are objects that are managed by another entity bean. They normally represent fine-grained business objects that are part of the entity bean. A dependent value class is a concrete class that the bean provider wishes to use internally within an entity bean or it is a class that is required to be exposed via the entity bean's remote or local interface. A dependent value class can be the value of a CMP field but it cannot be a value of a CMR field.

A6:

The EJB QL language has two syntaxes: a tag syntax and a query syntax.

A7:

The EJB QL language has three clauses: SELECT , FROM , and WHERE .

A8:

WebLogic Server has defined extensions to the EJB QL language and called it the WebLogic Query Language or WLQL. The WLQL language provides enhancements such as the DISTINCT clause, the ORDERBY clause, the ability to write subqueries, dynamic queries, and queries that return a result set.

Exercise

A1:

The following code demonstrates the answer to this exercise. The bean added to provide the functionality is called Invoice . The method findMaxInvoiceNo() uses WLQL and finds the maximum invoice number. Then the bean inserts a row into the database by incrementing the maximum number by one plus the price of the customer's bill.

In the Waiter Bean, only the getCheck() method has been changed, and hence only that method has been listed below. The ejb-jar.xml patch that is to be added to the existing ejb-jar.xml file and weblogic-cmp-rdbms-jar-invoice.xml file are also listed:

InvoiceHome.java 
package com.sams.learnweblogic7.ejb.cmp;

import java.rmi.RemoteException;
import javax.ejb.*;

public interface InvoiceHome extends EJBHome
{
   public InvoiceInterface findByPrimaryKey(InvoicePK key)
      throws FinderException, RemoteException;

   public InvoiceInterface findMaxInvoiceNo()
      throws FinderException, RemoteException;

   InvoiceInterface create(int invoiceNo, long itemPrice)
      throws CreateException, RemoteException;
}

InvoiceInterface.java:

package com.sams.learnweblogic7.ejb.cmp; 

import javax.ejb.EJBObject;

import java.util.Vector;

import java.util.Date;
import java.rmi.RemoteException;

import java.sql.Time;

import java.sql.Date;

public interface InvoiceInterface extends EJBObject
{
   public int getInvoiceNo() throws RemoteException;
   public void setInvoiceNo(int invoiceNo) throws RemoteException;

   public long getItemPrice() throws RemoteException;
   public void setItemPrice(long itemPrice) throws RemoteException;
}

InvoiceBean.java:

package com.sams.learnweblogic7.ejb.cmp; 

import java.sql.Time;
import java.sql.Date;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import java.util.Vector;
import java.util.Date;

abstract public class InvoiceBean implements EntityBean
{
   /**
    * The container assigned reference to the entity
    */
   private EntityContext context;

   public InvoiceBean() {
   }

   /**
    * return invoiceNo
    */
   abstract public int getInvoiceNo();

   /**
    * param invoiceNo
    */
   abstract public void setInvoiceNo(int invoiceNo);

   /**
    * return itemPrice
    */
   abstract public long getItemPrice();

   /**
    * param itemPrice
    */
   abstract public void setItemPrice(long itemPrice);

   /**
    * Sets the context of the bean
    * param ec
    */
   public void setEntityContext(EntityContext ec) {
      context = ec;
   }

   /**
    * Clears the context of the bean
    */
   public void unsetEntityContext() {
      this.context = null;
   }

   public void ejbActivate() {
   }

   public void ejbPassivate() {
   }

   public void ejbLoad() {
   }

   public void ejbStore() {
   }

   /**
    *
    * param invoiceNo
    * param itemPrice
    */
   public InvoicePK ejbCreate(int invoiceNo, long itemPrice) {
      setInvoiceNo(invoiceNo);
      setItemPrice(itemPrice);
      return null;
   }

   /**
    * param invoiceNo
    * param itemPrice
    */
   public void ejbPostCreate(int invoiceNo, long itemPrice) {
   }

   public void ejbRemove() {
   }
}

InvoicePK:

package com.sams.learnweblogic7.ejb.cmp; 

import java.io.Serializable;
import java.sql.Date;

public class InvoicePK implements Serializable
{
   public int invoiceNo;

   public InvoicePK() {
   }

   /**
    * return hashcode
    */
   public int hashCode() {
      return (invoiceNo);
   }

   /**
    * return boolean
    */
   public boolean equals(Object that) {
      if (!(that instanceof InvoicePK))
         return false;
      else
         return true;
   }
}

WaiterBean.java:

//called by the client, to get his check. 
public float getCheck(){
   long checkSum = 0;
   try{
      InvoiceHome invHomeObj = lookupInvoiceHome();

      // this finder method demonstrates WEBLOGIC-QL
      InvoiceInterface invoiceObj = invHomeObj.findMaxInvoiceNo();
      int maxInvoiceNo = invoiceObj.getInvoiceNo();
      maxInvoiceNo = maxInvoiceNo + 1;

      Enumeration orderedItemsEnum = orderedItemsList.elements();
      while(orderedItemsEnum.hasMoreElements()){
         Order individualCurrOrder = (Order)orderedItemsEnum.nextElement();
         checkSum += (individualCurrOrder.getItem()).getItemPrice()*
                 individualCurrOrder.getQty();
      }

      InvoiceInterface displayInvoiceObject =
              (InvoiceInterface)PortableRemoteObject.narrow(invHomeObj.
              create(maxInvoiceNo , checkSum),InvoiceInterface.class);
      System.out.println("Invoice No := " + maxInvoiceNo);
   }
   catch(Exception e){
      e.printStackTrace();
   }
   return checkSum;
}

ejb-jar.xml:

<entity> 
   <ejb-name>InvoiceEJB</ejb-name>
   <home>com.sams.learnweblogic7.ejb.cmp.InvoiceHome</home>
   <remote>com.sams.learnweblogic7.ejb.cmp.InvoiceInterface</remote>
   <ejb-class>com.sams.learnweblogic7.ejb.cmp.InvoiceBean</ejb-class>
   <persistence-type>Container</persistence-type>
   <prim-key-class>com.sams.learnweblogic7.ejb.cmp.InvoicePK</prim-key-
           class>
   <reentrant>False</reentrant>
   <abstract-schema-name>Invoice</abstract-schema-name>
   <cmp-field>
      <field-name>invoiceNo</field-name>
   </cmp-field>
   <cmp-field>
      <field-name>itemPrice</field-name>
   </cmp-field>
   <query>
      <query-method>
         <method-name>findMaxInvoiceNo</method-name>
            <method-params>
            </method-params>
      </query-method>
      <ejb-ql>
         The query has been written in weblogic-cmp-rdbms-jar-invoice.xml
         since this is to demonstrate the use of weblogic-ql
      </ejb-ql>
   </query>
</entity>

weblogic-cmp-rdbms-jar-invoice:

<!DOCTYPE weblogic-rdbms-jar PUBLIC 
 '-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB RDBMS Persistence//EN'
 'http://www.bea.com/servers/wls700/dtd/weblogic-rdbms20-persistence-
         700.dtd'>
 <weblogic-rdbms-jar>
    <weblogic-rdbms-bean>
       <ejb-name>InvoiceEJB</ejb-name>
       <data-source-name>ejb-datasource-learnweblogic7</data-source-name>
       <table-name>invoice</table-name>
       <field-map>
          <cmp-field>invoiceNo</cmp-field>
          <dbms-column>invoice_no</dbms-column>
       </field-map>
       <field-map>
          <cmp-field>itemPrice</cmp-field>
          <dbms-column>item_price</dbms-column>
       </field-map>
       <field-group>
          <group-name>invoiceGroup</group-name>
          <cmp-field>invoiceNo</cmp-field>
          <cmp-field>itemPrice</cmp-field>
       </field-group>
       <weblogic-query>
          <query-method>
             <method-name>findMaxInvoiceNo</method-name>
             <method-params>
             </method-params>
          </query-method>
          <weblogic-ql>
             <![CDATA[SELECT OBJECT(inv) FROM Invoice As inv
               WHERE inv.invoiceNo IN(SELECT MAX(inv2.invoiceNo) FROM
               Invoice AS inv2)]]>
          </weblogic-ql>
          <group-name>invoiceGroup</group-name>
          <!-- Use a group to specify that multi-media fields should not be
            read from the DB by this query. -->
          <max-elements>1000</max-elements>
          <include-updates>true</include-updates>
       </weblogic-query>
    </weblogic-rdbms-bean>
    <create-default-dbms-tables>True</create-default-dbms-tables>
</weblogic-rdbms-jar>

weblogic-ejb-jar.xml:

<weblogic-enterprise-bean> 
   <ejb-name>InvoiceEJB</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-invoice.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>Invoice_Home</jndi-name>
</weblogic-enterprise-bean>