ejb_unit3_session_bean by keralaguest

VIEWS: 6 PAGES: 33

									         Different Types Of EJB
                                        EJB

                 Entity                                  Session


 Bean managed        Container managed            Stateless             Stateful




    Session Bean


   • Two types of session beans:
         – Stateful
         – Stateless
   • Used to implement server-side business logic
   • Session beans can:
         – Access data
         – Participate in distributed transactions.
         – Invoke other beans.
         –
   • Session Beans are used to implement server-side business logic.
   • These are generally tied to the lifetime of a given client session.
   • When the client disconnects, the application server may destroy the session bean
     instance.
   • They are relatively short-lived.
   • Sessions beans are temporary, removed when EJB container is shutdown or
     crashes
   • Session beans are usable by one client at a time i.e., they are not shared among
     multiple clients.
   • Session beans can access data from database.

    • A session bean is required to implement the SessionBean interface.
        public interface javax.ejb.SessionBean extends
javax.ejb.EnterpriseBean
        {
                public abstract void ejbActivate();
                public abstract void ejbPassivate();
                public abstract void ejbRemove();
                public abstract void
             setSessionContext(SessionContext ctx);
       }
Ejb passivate():

    • Container calls this method to swap the EJB class out to “semi-persistent”
      storage.
    • Storage is semi-persistent becoz Session EJB do not guarantee for long life as
      Entity EJB do.
    • If the EJB container crashes or restarts, the session beans that existed before the
      crash or restart are destroyed.
    • Session bean also have an associated timeout value; after the timeout expires,
      they are destroyed.
    • If none of these events happens the session bean can be swapped back in at some
      later time.

Ejb activate() :

   • The ejbActivate() method is essentially the inverse of the ejbPassivate() call.
   • The container calls this method after a session bean‟s state has been restored from
       “semi-persistent” storage, but before it becomes available to the outside world.
   • A bean can use the ejbActivate() call to restore any resources that is closed before
       being passivated.
   • Example – If the bean had to close a file, it can reopen the file in ejbActivate().
Ejb remove() :




•      This method is invoked by the container as a
       result of a client calling the remove() method of
       a bean‟s home or remote interface.
•      The client‟s invocation of the remove() method
       notifies the container that this particular session
       bean instance should be destroyed.



Session Bean - ejbSetSessionContext()
                  • This method is called at the very beginning of a session bean‟s life.
                  • The container passes the session bean an object that implements the
                    SessionContext interface.
                  • The bean stores this object in an object variable, and can then use the
                    SessionContext to interact with container-provided services such as security and
                    transaction management.

Steps Involved In Creation Of Session Bean

                  • The client calls a create() method in the bean‟s home interface.
                  • The container sets aside storage for the EJBObject and EBJBean and instantiates
                    them.
                  • The container calls the object‟s setSessionContext() method.
                  • The container calls the ejbCreate() method whose signature matches the create()
                    method invoked by the client.
                  •

                                                 EJB LIFECYCLE

Client                                                       Server
                                           Client locates
                                           the               JNDI
                                                               Name
                                           bean’s home
 Home interface




                                        Server returns
                                        reference

                                                             Container

                                           Client calls                                                 * Bean class
                                           home.create(
                                           )                                                             newInstance(
                                                                              Home                             )
                     Remote interface




                                         Returns reference              create(        ejbCreate(
                                         to                             )                  )            SessionContext
                                         EJBObject

                                                                          EJBObject                    SessionBean
                                                                                           Interface




                                        Invoke method on
                                                             * Remote




                                        bean


                                            Return
                                            result


                                                                                  * Bean writer provides



Types of Session Bean
    • There are two types of session Beans
         – Stateless session bean is one that doesn’t keep track of any information
             from one method call to another essentially, a bean with no instance
             variables.
      (Ex: CalculateSalesTax Bean).
         – Stateful session bean, is a bean that changes state during a conversation
             – that is, a bean that has instance variables.
      (Ex: ShoppingCart Bean)


S.N   Stateless SessionBean               Stateful SessionBean
1     Def                                 Def
2     Any two instances of a stateless    Any two instances of a stateless
      bean are equivalent                 bean are not equivalent

3     A container can easily handle a Life cycle of a stateful bean is more
      stateless Session bean.         complex for the container

4     Instances of a stateless bean can Instance creation and deletion is
      be created and destroyed at        complex because, the container have
      will, without worrying about their to maintain the state of the stateful
      state at the time of their         session bean during swap out &
      destruction.                       swap in process.
5     A stateless session bean can have   A stateful session bean can
      only one ejbCreate() method, it     implement any number of
      does not require any                ejbCreate() methods that take
      arguments.                          different sets of arguments.
6     Ex:CalculateSalesTax Bean           Ex:ShoppingCart Bean
  Lifecycle - Stateless Session Bean
 •     Stateless session bean has only two states:
        –    Non-existence
        –    Method-ready state




Lifecycle - Stateless Session Bean

   • newInstance() – Allocates space for the bean and brings it into existence state.
   • setSessionContext() – Gives the bean a Session Context.
   • ejbCreate() – Allows the bean to perform any necessary initializations
   • A stateless session bean can have only one ejbCreate() method, Because a
     stateless session bean has no specific state variables, it does not require any
     arguments.
   • Because stateless beans have no state, they can be reused by many clients in the
     course of their existence.
   • Even though the client invokes create() and remove(), these methods do not
     necessarily result in an actual instance being created or removed in the container.
   • The container will maintain a pool of stateless beans. This pool will be large
     enough to ensure that any client that needs to invoke a method receives an
     instance.
Lifecycle - Stateful Session Bean
    Lifecycle - Stateful Session Bean
•    newInstance() – Allocates space for the bean and brings it – into
     existence.
•    setSessionContext() – Gives the bean a SessionContext
•    ejbCreate() – Allows the bean to perform any necessary
     initializations.
•    A stateful session bean can implement any number of
     ejbCreate() methods that take different sets of arguments.
•    Once the ejbCreate() method executes the bean enters the
     “method ready” state.
•    Three transitions out of this state(“method-ready”) are possible.
      –   The bean can enter a transaction
      –   It can be passivated
      –   It can be removed.
•    The bean enters a transaction if one of its transactional methods
     is invoked. (should contain transaction declaratory
     TX_BEAN_MANAGED, TX_REQUIRED, TX_REQUIRES_NEW,
     TX_MANDATORY, for TX_SUPPORTS)
    Lifecycle - Stateful Session Bean
•    If the bean implements the SessionSynchronization interface,
     the container invokes its afterBegin() method to notify it that it
     is entering a transaction.
•    The bean then moves to the “method-ready in transaction”
     state, where it remains until the transaction concludes.
•    If the transaction was created specifically for the method
     invocation, the bean will exit the “method-ready in transaction”
     state immediately.
•    If a commit occurs while the bean is in the “method-ready in
     transaction” state, the beforeCompletion() method of the
     SessionSynchronization interface is invoked with a boolean value
     of true as the argument.
•    This sequence of invocations allows the bean to perform any
     database updates, before the transaction commits, and provides
     it with definitive notification that the transaction has successfully
     committed. After these methods finish the bean returns to the
     “method-ready” state.
    Lifecycle - Stateful Session Bean
•    On the other hand, if a rollback occurs while the bean is
     in     the “method-ready       in   transaction”   state,
     beforeCompletion()     is     not     invoked;     rather
     afterCompletion is invoked with a boolean argument of
     false.
•    When the bean is passivated, the container invokes its
     ejbPassivate() method and then writes it out to some
     type of semi-persistent storage; it also removes the bean
     from memory.
•    If the bean have opened any database or socket
     connections from the ejbCreate() method, the code
     should included in the ejbPassivate() method to close
     these connections.
•    These connections are reestablished again when the
     beans are activated.
    Lifecycle - Stateful Session Bean
•    The final transaction is out of the “method-ready” state is
     caused by the removal of the bean.
•    Unlike stateless session beans, stateful session beans are
     actually removed by the container in response to a
     client‟s call to the remove() method on the bean‟s remote
     interface.
•    Before removing the bean, the container calls the beans
     ejbRemove() method, which gives it one last opportunity
     to write out database updates before it passes out of
     existence. This will close all the opened database and
     socket connections.
•    After ejbRemove() has executed, the bean is destroyed
     and cannot be resurrected.




                        EJB - Implementaion
                  SQL Queries
•   Select cust_id, cust_name, add from customer;
•   Select count(*) from inventory;
•   Select itemcode,     itemdesc,    quantity,   price   from
    inventory;
•   Select Max(cust_id) from customer;
•   Insert into customer (cust_id, cust_name, add) values
    (100, „Kamal‟, „MCA II Yr, PCE‟);
•   Insert into customer (cust_id, cust_name, add) values (?,
    „?‟, „?‟);
•   Update orders set quantity=10 wher cust_id=100 and
    itemcode=„1000‟;
•   Delete   from    orders    where      cust_id=100     and
    itemcode=„1000‟;
               DB Connectivity
DB – Connectivity Creation
private Connection C;
private SessionContext ctx;
pusblic String databaseURL;
public String JDBCDriverName;
Properties props=ctx.getEnvironment()
databaseURL=(String) props.get(“bagBean.databaseURL”)
JDBCDriverName=(String)
    props.get(“bagBean.JDBCDriverName”)
Class.forName(JDBCDriverName).newInstance()
C=DriverManger.getConnection(databaseURL)




          DB Query Execution

•   DB – Query Execution
String query=“select * from
    customer”
Statement
    stmt=c.createStatement(
    );
ResultSet
    rs=stmt.executeQuery(st
    mt);
rs.getString(1) or
     rs.getInt(1)
rs.next()
                          Example
                      Online Shopping
                   (Stateful Session Bean)


    Online Shopping - Requirements
•   It should allow the user to order items.
•   It should allow the user to remove an item from
    the shopping bag
•   It should allow      the     user        to   interact   with
    inventory DB
•   It should not allow the user to place an order if
    the item is not currently in stock.
•   The system should             relatively        small    and
    straigtforward.
     Online Shopping - Design
Some of the Business Methods
orderItem() – It is used to place order for particular item. It
     takes two args itemcode and custid
removeItem() – It is used to remove ordered item from
     shopping bag. It also takes itemcode and custid args
createCustomer() – Used to create new customers into the
     database. Takes name and add as arguments and return
     custid.
finalizeOrder() – Used to execute the order once the
     customer is satisfied with the shopping bag‟s contents.
 Online Shopping – DB Design
INVENTORY Table
       ITEMCODE VARCHAR(5)
       ITEMDESC VARCHAR(64)
       QUANTITY SMALLINT
       PRICE        DOUBLE PRECISION

CUSTOMER Table
       CUST_ID SMALLINT
       CUST_NAME   VARCHAR2(64)
       CUST_ADDR   VARCHAR2(64)

ORDERS Table
       CUST_ID SMALLINT
       ITEMCODE VARCHAR(5)
       QUANTITY SMALLINT
     EJB - Implementaion
•   Create Remote interface
•   Create Home interface
•   Create bean implementation class
•   Compile Remote interface, Home interface and
    implementation class.
•   Create Session/Entity descriptor
•   Create manifest
•   Create ejb-jar file
•   Deploy the ejb-jar file.
•   Write a client
•   Run the client.
1. Create Remote interface
package book.bag;
import javax.ejb.*;
import java.rmi.*;
public interface BagRemote extends EJBObject
{
   public void addItem(String itemcode, int quantity)
     throws RemoteException, ItemNotFoundException;
   public void removeItem(String itemcode, int quantity)
     throws RemoteException, ItemNotFoundException;
   public void finalizeOrder() throws RemoteException;
}




2. Create Home interface
package book.bag;
import javax.ejb.*;
import java.rmi.*;
public interface BagHome extends EJBHome
{
   public BagRemote create(int custid)
     throws RemoteException, CreateException;
   public BagRemote create(String name, String addint
   custid)       throws RemoteException, CreateException;

}
                            InventoryItem - Class


package book.bag;
import javax.io.*;
public class InventoryItem implements Serializable
{
    public String itemcode;
    public String itemdesc;
    public int quantity;
    public double price;
}




 3. Create Bean Implementation Class
package book.bag;
import javax.ejb.*;
import java.rmi.*;
import java.sql.*;
import java.util.HashTable;
public class BagBean implements SessionBean
{
    public int custid;
    public InventoryItem inventory[];
    public Hashtable bag=new Hashtable();
    private Connection C;
    private SessionContext ctx;
    pusblic String databaseURL;
    public String JDBCDriverName;




     public void ejbCreate(String name, String add)
                                        throws CreateException
 {   init();
             try
             {      C=DriverManger.getConnection(getDBURL());    }
             catch(Exception e){                            }
             initInventory();
             this.custid=createCustomer(name,add);
      }
      public void ejbCreate(int custid) throws CreateException
  {   init();
              try
              {       C=DriverManger.getConnection(getDBURL());       }
              catch(Exception e){                              }
              initInventory();
              this.custid=custid;
      }


      public void init() throws CreateException
  {
              Properties props=ctx.getEnvironment()
              databaseURL=(String) props.get(“bagBean.databaseURL”)
              JDBCDriverName=(String)
props.get(“bagBean.JDBCDriverName”)
              try
              {
                     Class.forName(JDBCDriverName).newInstance()
              }
              catch(Exception e)
              {
              }
       }


      public void init() throws CreateException
      {
       Properties props=ctx.getEnvironment()
       databaseURL=(String)
      props.get(“bagBean.databaseURL”)
       JDBCDriverName=(String)

      props.get(“bagBean.JDBCDriverName”)
       try
       {

       Class.forName(JDBCDriverName).newInst
      ance()
       }
       catch(Exception e)
       public void initInventory() throws CreateException
  {    String query=“select cound(*) from inventory;
               try{Statement stmt=C.createStatement();
               ResultSet rs=stmt.executQuery(query);         rs.next()
               int count=rs.getInt(1);
               inventory=new InventoryItem[count];
               query=“select * from inventroy”;
               rs=stmt.executeQuery(query);                          rs.next();
               for(int i=0;i<count;i++)
                 {      inventory[i]=new InventoryItem();
                        inventory[i].itemcode=rs.getString(1);
                        inventory[i].itemdesc=rs.getString(2);
                        inventory[i].quantity=rs.getInt(3);
                        inventory[i].price=rs.getDouble(4); rs.next() }
               }//end of try block
               catch(Exception e){                                       }
       }

       public int createCustomer(String name, String add)
       {       try
               { String query=“insert into customer values( (select max(cust_id) from
custromer+1,‟ ” + name + “ „ “ + add +” „ “);
               Statement stem=C.createStatment()
               ResultSet rs=stmt.executQuery(query);
               stmt.close();
               stmt = C.creatStatement();
               qurey=“select MAX(cust_id) from customer”;
               Resultset rs=stme.executQuery(query);
               rs.next();
               int custid=rs.getInt(1);
               rs.close();
               stmt.close();
               return custid;
               }       // End of try block
               catch(Exception e){                                    }
       }


       public void getCustID()
  {
              return custid;
       }

       public void getDBURL()
  {
              return databaseURL;
    }

    public void ejbActivate()
{   try
            {       C=DriverManger.getConnection(getDBURL());   }
            catch(Exception e){                          }
    }
    public void ejbPassivate()
{   try
            {       C.close();                           }
            catch(Exception e){                          }
    }
    public void ejbRemove()
    {       try
            {       C.close();                           }
            catch(Exception e){                          }
    }
    public void setSessionContext(SessionContext ctx)
    {       this.ctx=ctx;                                }

    public void addItem(String itemcode, int quantity)
                                throws ItemNotFoundException
{
          if (bag.containsKey(itemcode) )
          {
                  InventoryItem i=bag.get(itemcode);
                  i.quantity=i.quantity+quantity;
          }
          else
          {
                  InventoryItem i=findItem(itemcode);
                  i.quantity=quantity;
                  bag.put(itemcode,i);
          }
    }


    public void removeItem(String itemcode, int quantity)
                               throws ItemNotFoundException
{
          if (bag.containsKey(itemcode) )
          {
                  InventoryItem i1=bag.get(itemcode);
                  if(i1.quantity<=quantity)
                  {
                          bag.remove(itemcode);
                     }
                     else
                     {
                            i1.quantity=i1.quantity-quantity;
              }
       }


       public void finalizeOrder()
       {       try
               {
               InventoryItem i1[]=new InventoryItem[bag.size()];
               i1.getbagContents();
               String query=“insert into orders values(?,?,?)”;
               PreparedStatement ps=C.PreparedStatement(query);
               for(int i=0;i< i1.lengthli++)
               {        ps.setInt(1,this.custid);
                        ps.setString(2,i1[i].itemcode);
                        ps.setInt(3,i1[i],quantity);
                        ps.executeUpdate();
               }
               }
               catch(Exception e)
               {                                                 }
       }
}//End of BagBean
    4. Compile Remote interface, Home interface
                and Implementation class

•     javac BagRemote.java
•     javac BagHome.java
•     javac BagBean.java
             Or
•     Javac *.java
              5. Create Session Descriptor


•    Session descriptor contains information about how to
     deploy the bean.
•    Most EJB servers are supplied with graphical tools for
     constructing the deployment descriptor.



                6. Create Manifest file
•     Manifest file is a text document that contains information
      about the contents of a jar file.
•     jar utility automatically create manifest if none exist.
       Name: book/bag/BagBeanDD.ser
       Enterprise-Bean:True



                     7. Create ejb-jar file

•    jar cmf book\bag\manifest bagbean.jar
                book\bag
                            Example
                        Online Shopping
                    (Stateless Session Bean)




1. Create Remote interface
package book.bag;
import javax.ejb.*;
import java.rmi.*;
public interface BagRemote extends EJBObject
{
   public void addItem(int custid,String itemcode,int
   quantity)
     throws RemoteException, ItemNotFoundException;
   public void removeItem(int custid,String itemcode,int
   qunt) throws RemoteException, ItemNotFoundException;
   public void finalizeOrder() throws RemoteException;
}
2. Create Home interface
package book.bag;
import javax.ejb.*;
import java.rmi.*;
public interface BagHome extends EJBHome
{
   public BagRemote create()
    throws RemoteException, CreateException;
}




              InventoryItem - Class
package book.bag;
import javax.io.*;
public class InventoryItem implements Serializable
{
    public String itemcode;
    public String itemdesc;
    public int quantity;
    public double price;
}
     3. Create Bean Implementation Class
package book.bag;
import javax.ejb.*;
import java.rmi.*;
import java.sql.*;
import java.util.HashTable;
public class BagBean implements SessionBean
{   public void init() throws CreateException
  { Properties props=ctx.getEnvironment()
      databaseURL=(String) props.get(“bagBean.databaseURL”)
      JDBCDriverName=(String)
                      props.get(“bagBean.JDBCDriverName”)
      try{Class.forName(JDBCDriverName).newInstance() }
      catch(Exception e){                          }
    }




      public void ejbCreate() throws CreateException
 {
             init();
      }
      public void getCustID()
 {
             return custid;
      }

      public void getDBURL()
 {
             return databaseURL;
      }


      public void ejbActivate()
 {
      }
      public void ejbPassivate()
 {
      }
      public void ejbRemove()
      {
      }
      public void setSessionContext(SessionContext ctx)
      {
             this.ctx=ctx;
      }

      public void addItem(int custid,String itemcode, int quantity)
                                   throws ItemNotFoundException
  {

  }

      public void removeItem(String itemcode, int quantity)
                                 throws ItemNotFoundException
  {

  }

      public void finalizeOrder()
      {

       }
}//End of BagBean

  4. Compile Remote interface, Home interface
              and Implementation class
 •    javac BagRemote.java
 •    javac BagHome.java
 •    javac BagBean.java
             Or
 •    Javac *.java

                 5. Create Session Descriptor
•     Session descriptor contains information about how to
      deploy the bean.
•     Most EJB servers are supplied with graphical tools for
      constructing the deployment descriptor.
              6. Create Manifest file
•   Manifest file is a text document that contains information
    about the contents of a jar file.
•   jar utility automatically create manifest if none exist.
     Name: book/bag/BagBeanDD.ser
     Enterprise-Bean:True



                   7. Create ejb-jar file

•   jar cmf book\bag\manifest bagbean.jar
               book\bag



                            Entity Bean


                  Entity Beans

• Entity Beans are persistent
     –   Data exists even after database is shut
         down
          •   customers, products, accounts, and orders
              (business entities)
          •   each entity bean has a underlying table in a relational
              database
          •   each instance corresponds to a row in the table

     –   state persistent, transactional, shared
         among clients
          •   hides complexity, work within transactions
          •   contain data related logic such as inserting,
              updating and removing a record
                Entity Beans

• Container-Managed Persistence
  (CMP )
   –   The EJB container manages the persistence
        •   uses deployment descriptor
        •   changes saved automatically in the database
        •   no code is required in the bean to manage database

• Bean-Managed Persistence                        (BMP )
   –   The methods in the bean manages the
       persistence
        •   will manage database connections
        •   manages changes in the bean as well
            Developing Entity Beans

     • Writing the primary key class (if
           needed)
     • Writing the bean class
     • Writing the home and remote
Instructor Notes
Writing entity beans is similar to writing session beans, except you must write a primary key class, if
needed, and finder methods.
           interfaces
You need to think about transactions when developing entity beans, because each call to an entity
bean may re-get the information and then throw it away. A couple approaches to minimize this are:
1. Start the transaction, read in the info, perform functions, then commit.
2. Use a session bean to manage the transaction and be the front for the entity bean. This keeps
you from having to write transaction management code, and allows the container to handle
transactions more expertly. Set the session bean to use an existing transaction if there is one, else
start a new one.
Entity Bean
            Message Bean




    Entity vs Session Beans

Entity Bean           Session Bean
•   business entity   •   task, agent
•   shared access     •   not shared
•   long-lived        •   short-lived
•   survive crashes       (relative)

•   e.g. Account      •   lost on crashes
                      •   e.g. shoppingCart

								
To top