Docstoc

EJB_entity_beans

Document Sample
EJB_entity_beans Powered By Docstoc
					                                                   Enterprise
                                                        Java




                  Entity Beans

          Container and Bean Managed Persistence




v041102                 Entity Beans                      1
                                         Enterprise
                                              Java

                         Topics
• Understanding Entity Beans
• Implementing Entity Beans
     – Container Managed Persistence
     – Bean Managed Persistence




v041102                   Entity Beans          2
                                       Enterprise
                                            Java




          Understanding Entity Beans




v041102             Entity Beans              3
                                                                   Enterprise
                                                                        Java

                      Enterprise Bean
• Component that can be deployed in any EJB-compliant
  application server
• Component interface for its operations (Remote and Local)
• Home Interface for create, find, and remove (Remote and
  Local)
• Bean Implementation
     – implements business methods
     – implements finder (BMP Entity), home (2.0 Entity), and Select
       (2.0 CMP Entity) methods




v041102                         Entity Beans                              4
                                                        Enterprise
                                                             Java

                            Bean Types
• Entity Beans
     – Represents persistent data in a database
          • Account and deposit()
     – Exists indefinitely
     – Bean-managed and Container-managed persistence
• Session Beans
     – Represents business logic operations
          • Teller and transfer()
     – Stateless and Stateful
     – Exist for lifetime of client session
v041102                             Entity Beans               5
                                                        Enterprise
                                                             Java

                      Bean Types
• Message Beans
     – Stateless component invoked using asynchronous
       message (JMS)




v041102                   Entity Beans                         6
                                                                                     Enterprise
                                                                                          Java

                      Container and Beans
            create                         JVM
            find
                                                                     Container
                 Remote Home Stub                    Remote Home
Remote
Client
                 Remote Object Stub                  Remote Object
                                                                             EJB Class
                                                                           EJB Class
                                                                          EJB Class
                                                      Local Home                 Bean Pool
           deposit                       Local
           transfer                      Client
                                                     Local Object




 v041102                              Entity Beans                                           7
                                                   Enterprise
                                                        Java

           Entity Bean (from Spec)
• Provides an object view of data in the database
• Allows shared access from multiple users
• Can be long-lived (lives as long as the data in the
  database)
• The entity, its primary key, and its remote
  reference survive the crash of the EJB container




v041102                 Entity Beans                      8
                                                                              Enterprise
                                                                                   Java

                       Entity Bean Support
• Optional in EJB 1.0
• Required in EJB 1.1
• Revised in EJB 2.0
     – Added Abstract Schemas
     – Added EJB Query Language which is portable across different database
       technologies (even though it is similar to SQL)
     – Added Container Managed Relationships
     – EJB 1.1 support still a requirement in EJB 2.0
• EJB 2.1
     – J2EE 1.4, timers, ELB-QL updates
• EJB 3.0 radical changes (early draft review)
     –    Annotations for persistence mappings
     –    No home or component interface
     –    Hibernate-inspired
     –    Not an abstract class


v041102                                 Entity Beans                                 9
                                                                                                             Enterprise
                                                                                                                  Java

                          Entity Bean Lifecycle
                                              Does Not Exist


      unload bean                                                               bean instance
      ins tance()/unsetEntityContext();                                         required/Class.new Instance();
      f inalize()                                                               setEntityContext()
                                                   Pooled
   passivate object()/ejbPassivate




                                                                      this.ejbSelect()

                     Home.f ind()/ejbFind()                                    Home.XXX()/ejbHomeXXX()


                                                        Home.c reate()/ejbCreate();
                  object.remove()/ejbRemove()           ejbPostCreate()
                                                                           activate object()/ejbActivateObject
                                                Ready




                   object.method()/ejbLoad();               this.ejbSelect()
                   business method(); ejbStore()

v041102                                            Entity Beans                                                    10
                                                          Enterprise
                                                               Java

                   Entity Bean States
• Does Not Exist
     – no instance instantiated
     – default state at container startup
• Pooled
     – state entered when container offers component
     – state re-entered when object disassociated from bean
• Ready
     – state where business methods can be invoked


v041102                      Entity Beans                       11
                                                                       Enterprise
                                                                            Java

                 Entity Bean Transitions
• Does Not Exist -> Pooled
     – methods invoked
          • Class.newInstance() (default constructor)
              – usually not provided/no behavior
              – place all bean initialization code in setEntityContext and
                object initialization in ejbCreate/ejbPostCreate
          • setEntityContext(EntityContext ctx)
              – establish EJB’s reference to container (ctx)




v041102                           Entity Beans                               12
                                                                          Enterprise
                                                                               Java

                 Entity Bean Transitions
• Pooled -> Ready (via creation)
     – occurs when client invokes a Home.create(<args>)
     – object created, bean instance located
     – methods invoked
          • ejbCreate(<args>)
              – may establish properties
              – must establish primary key
              – object not yet ready to be advertised
          • ejbPostCreate(<args>)
              – establish relationships (object ready to be advertised)


v041102                           Entity Beans                                  13
                                                                    Enterprise
                                                                         Java

                 Entity Bean Transitions
• Pooled -> Ready (via query)
     – occurs when Home.find (<args) or
       this.ejbSelect(<args>) invoked to return objects
     – bean selected from pool, associated with object
     – methods invoked
          • ejbActivate()
              – called after object associated with bean instance
              – no transaction or security context
              – no interaction with database



v041102                          Entity Beans                             14
                                                                   Enterprise
                                                                        Java

                 Entity Bean Transitions
• Ready -> Pooled (passivation)
     – occurs after ejbStore() and just prior to disassociating
       object from bean
     – bean returned to pool
     – methods invoked
          • ejbPassivate()
              – simply a notification
              – no state serialized as in Stateful Session Beans
              – no interaction with database



v041102                           Entity Beans                           15
                                                                       Enterprise
                                                                            Java

                 Entity Bean Transitions
• Ready -> Pooled (removal)
     – occurs when client invokes object.remove()
     – bean returned to pool
     – methods invoked
          • ejbRemove()
              – must release any object-specific resources (identical to
                ejbPassivate())
                   » may call ejbPassivate() within ejbRemove()
              – called prior to database removal in CMP
              – called to remove from database in BMP


v041102                           Entity Beans                               16
                                                                   Enterprise
                                                                        Java

                Entity Bean Transitions
• Ready State
     – occurs when client invokes object.<business method>()
     – bean activated from pool
     – methods invoked
          • ejbLoad()
              – synchronize cache with database (read from database)
              – called after db load in CMP; command to load in BMP
          • business method
          • ejbStore()
              – synchronize cache with database (write to database)
              – called prior to db store in CMP; command to store in BMP
v041102                         Entity Beans                             17
                                          Enterprise
                                               Java




          Implementing CMP Entity Beans




v041102               Entity Beans              18
                                                          Enterprise
                                                               Java

      Creating a Book CMP Entity Bean
• (Create the Primary Key Class)
     – if required
• Create Value Objects
• Create the Local/Remote Object Interface
     – *Entity Beans should only be accessed by Session
       Facades through their local interfaces
• Create the Local/Remote Home Interface
• Create the Bean Class
• Create the Deployment Descriptors

v041102                    Entity Beans                         19
  ...ejb.enti ty.bean.BookEJB


                java.lang.String

  -ctx_:EntityContext
                                   Entity Bean Class               Enterprise
                                                                        Java


  -PRINT_DEBUG:boolean

  +ejbActivate:v oid
  +ejbPassivate:void
  +ejbLoad:void
  +ejbStore:void
  +ejbRemove:void
  +setEntity Context:void
  +unsetEntityContext:void
  #log:void
   id:String
   author:String                       container.BookEJB_Impl
   title:String                        <abstract method impls>
   topic:String
                                     <concrete method interpose>
  +ejbCreate:String
  +ejbPostCreate:void
  +ejbCreate:String
  +ejbPostCreate:void



  +setId:void
  +getId:String
  +setAuthor:void
  +getAuthor:String
  +setTitle:void
  +getTitle:String
  +setTopic:void
  +getTopic:String
v041102                                     Entity Beans                 20
                                                                                Enterprise
                                                                                     Java

                                   EJBContext
                           interf ace
                    j avax.ej b.EJBContext                             interf ace
                                                              j avax.ej b.SessionContext


    +getCallerIdentity:java.security.Identity
    +getCallerPrincipal:java.security.Principal             +getEJBObject:javax.ejb.EJBObject
    +getEJBHome:javax.ejb.EJBHome
    +getEnvironment:java.util.Properties                    EJBObject:javax.ejb.EJBObjec t
    +getRollb ackOnly:boolean
    +getUserTransaction:javax.transaction.UserTransaction
    +isCallerInRole:b oolean                                           interf ace
    +isCallerInRole:b oolean                                    j avax.ej b.EntityContext
    +setRollb ackOnly:void

     callerIdentity:java.security.Identity
     callerPrinc ipal:jav a.security.Principal               +getEJBObject:javax.ejb.EJBObject
     EJBHome:javax.ejb.EJBHome                               +getPrimaryKey:java.lang.Objec t
     environment:java.util.Properties
     rollbackOnly:boolean                                     EJBObject:javax.ejb.EJBObjec t
     userTrans action:javax.transaction.UserTransaction       primaryKey:jav a.lang.Object




v041102                                      Entity Beans                             21
                                               Enterprise
                                                    Java

              PrimaryKey Class
• Uniquely Identifies Object within database
• Two Objects are considered the same if they have
  the same Home and their PrimaryKey objects are
  equal
• Single primary keys can be mapped to java.lang
  classes (e.g. java.lang.String)
• Single primary keys may optionally be
  implemented with a custom Primary Key Class
• Compound primary keys must be implemented
  with a custom Primary Key Class
v041102               Entity Beans                   22
                                                         Enterprise
                                                              Java

                PrimaryKey Classes
• key values
     – must be legal RMI-IIOP types
     – must match in type and name with declaration in the
       bean class
     – must be public
• class must implement a Default Constructor,
  hashCode() and equals() methods
• must be Serializable


v041102                    Entity Beans                        23
                                                                      Enterprise
                                                                           Java

             Create the PrimaryKey Class
package corej2ee.examples.entitybooks;
import java.io.Serializable;
public class BookPK implements Serializable {
  public String id;
  public BookPK()        {}          //this one is required
  public BookPK(String id) { this.id = id; } //this one is optional

    public String toString() { return id; }
    public int hashCode()    { return id.hashCode(); }
    public boolean equals(Object rhs) {
      try { return ((BookPK)rhs).id.equals(id); }
      catch (Throwable ex) { return false;}
    }
}

v041102                               Entity Beans                          24
                                                              Enterprise
                                                                   Java

                     Value Objects
• Used to transfer data between the EJB Tier and
  client-tiers
• Pass-by-Value semantics
• Also called “Data Transfer Objects” (DTOs)
• Very similar to structs
• Used by bulk accessors
     – bulk accessor interfaces usually declared in Session
       Façade Remote


v041102                     Entity Beans                            25
                                                                         Enterprise
                                                                              Java

              Create Book Value Objects
package corej2ee.examples.entitybooks;
import java.io.Serializable;
public class Book implements Serializable {
   private String id_; private String title_;
   private String author_; private String topic_;
   public Book() {}
   public Book(String id, String title, String author, String topic) {
     id_ = id;    title_ = title; author_ = author; topic_ = topic; }
   public String getId()         { return id_; }
   public String getTitle()       { return title_; }
...
   public void setTitle(String title) { title_ = title; }
...
}
v041102                             Entity Beans                               26
                                               Enterprise
                                                    Java

                   Object Interface
• Defines the business methods to be implemented
  by the Bean that can be invoked by a client
• Arguments and return types must be legal RMI-
  IIOP types
• Local Interface
     – fine-grain access from Session Façade
• Remote Interface
     – larger-grain bulk accessors


v041102                    Entity Beans              27
                                                                Enterprise
                                                                     Java

                  Local Object Interface
• Must extend javax.ejb.EJBLocalObject
• Methods may not throw
  javax.ejb.RemoteException
package corej2ee.examples.entitybooks.ejb;
public interface BookLocal extends javax.ejb.EJBLocalObject {
  String getId();
  String getTitle();
  String getAuthor();
  String getTopic();
  void setTitle(String title);
  void setAuthor(String author);
  void setTopic(String topic);
}
v041102                           Entity Beans                        28
                                                        Enterprise
                                                             Java

                Remote Object Interface
• Must extend javax.ejb.EJBObject
• Methods throw java.rmi.RemoteException
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface BookRemote extends EJBObject {
  Book getValues() throws RemoteException;
  void setValues(Book values) throws RemoteException;
}


v041102                           Entity Beans                29
                                                                        Enterprise
                                                                             Java

                        Home Interface
• create<Suffix>() and create<Suffix>( args )
     – creates row in database
     – optional with entity beans
     – must have matching ejbCreate<Suffix>() and ejbPostCreate<Suffix>()
       methods in bean implementation if present
• find()
     – findByPrimaryKey(<primary key class>) is mandatory
     – other finders can be implemented
          • ex. findByName(String firstName, String lastName);
          • ex. findByAddress(String address);
              – return types include java.util.Collection and java.util.Set
• <home methods>() - work on table as a whole
v041102                           Entity Beans                                30
                                                                           Enterprise
                                                                                Java

            Create Local Home Interface
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EJBLocalHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;

public interface BookLocalHome extends EJBLocalHome {
  BookLocal create(String id) throws CreateException;
  BookLocal create(String id, String title, String author, String topic)
   throws CreateException;
  BookLocal findByPrimaryKey(String pk) throws FinderException;
  Collection findAll() throws FinderException;
}

v041102                               Entity Beans                               31
                                                                        Enterprise
                                                                             Java

                Local Creation Example
InitialContext jndi = new InitialContext();

BookLocalHome bHome =(BookLocalHome)
  jndi.lookup("java:comp/env/ejb/BookLocalHome");

BookLocal bookLocal = bHome.create(
   book.getId(), book.getTitle(), book.getAuthor(), book.getTopic());




v041102                           Entity Beans                                32
                                                                          Enterprise
                                                                               Java

          Create Remote Home Interface
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.rmi.RemoteException;
import java.util.Collection;
public interface BookRemoteHome extends EJBHome {
  BookRemote create(String id) throws CreateException, RemoteException;
  BookRemote create(Book values)
   throws CreateException, RemoteException;
  BookRemote findByPrimaryKey(String pk) throws FinderException;
  Collection findAll() throws FinderException, RemoteException;
}

v041102                           Entity Beans                                  33
                                                     Enterprise
                                                          Java

              Remote Creation Example
InitialContext jndi = new InitialContext();

BookRemoteHome bHome =(BookRemoteHome)
 PortableObjectRemote.narrow(
  jndi.lookup("java:comp/env/ejb/BookRemoteHome"),
             BookRemoteHome.class);

BookRemote bookRemote = bHome.create(book);




v041102                           Entity Beans             34
                                                        Enterprise
                                                             Java

                   Create the Bean Class
package corej2ee.examples.entitybooks.ejb;

import javax.ejb.EntityBean;
import javax.ejb.EntityContext;

public abstract class BookEJB implements EntityBean {
 /** This is our reference into the container. */
 private EntityContext ctx_;

…

}


v041102                           Entity Beans                35
                                                   Enterprise
                                                        Java

          Define the Abstract Accessors
  public abstract void setId(String id);
  public abstract String getId();
  public abstract void setAuthor(String author);
  public abstract String getAuthor();
  public abstract void setTitle(String title);
  public abstract String getTitle();
  public abstract void setTopic(String topic);
  public abstract String getTopic();

v041102                Entity Beans                      36
               Implement the Bean Class                            Enterprise
                                                                        Java



                  Business Methods
public Book getValues() {
  return new Book(getId(), getTitle(), getAuthor(), getTopic());
}

public void setValues(Book values) {
   setTitle(values.getTitle());
   setAuthor(values.getAuthor());
   setTopic(values.getTopic());
}




v041102                              Entity Beans                        37
                                                                             Enterprise
                                                                                  Java

          Coordinate Access to Container
/** This method is invoked after the bean class is instantiated and just
   prior to being available in the pool. The bean should acquire any
   object-neutral resources at this point. Note that the bean is not
   associated with an object at this point and any calls to the
   context's getPrimaryKey() will result in an exception. */
 public void setEntityContext(EntityContext ctx) { ctx_ = ctx; }

 /** This method is invoked just after removing the bean from the pool and
   finalizing it. The bean should release any object-neural resources at
   this point. Note that the bean is not associated with an object at
   this point and any attempt to access the primary key or abstract data
   model will result in an error. */
 public void unsetEntityContext() { ctx_ = null; }

v041102                             Entity Beans                                   38
                 Implement Bean Class                                  Enterprise
                                                                            Java



                   Create Methods
/**
  This method must set the primary key for the object and optionally
  set any of the fields that will get mapped into the database. */
public String ejbCreate(String id) throws CreateException {
  setId(id);
  return null; //container gets primary key another way
}

/**
  This method is where we establish any relationships to our object. */
public void ejbPostCreate(String id) {}


v041102                          Entity Beans                                39
                 Implement Bean Class                                     Enterprise
                                                                               Java



                 Create Methods (cont.)
public String ejbCreate(String id, String title, String author, String topic)
   throws CreateException {
  setId(id);
  setTitle(title);
  setAuthor(author);
  setTopic(topic);
  return null; //container gets primary key another way
}
public void ejbPostCreate(
  String id, String title, String author, String topic) {
}


v041102                           Entity Beans                                  40
                 Implement Bean Class                             Enterprise
                                                                       Java



                   Remove Method
/**
  This method is called just before the row(s) representing the
  abstract data model get removed from the database.
*/
public void ejbRemove() {
  log("BookEJB.ejbRemove:" + getId() + ":" + getTitle());
}




v041102                          Entity Beans                           41
              Implement Bean Class                                    Enterprise
                                                                           Java



          Resource Management Methods
/** This method is invoked just after the bean is associated with an
  object. We have a primary key, but out abstract data model has not
  yet been synchronized with the database. We can allocate any
  object-specific resources (that do not depend on the database values)
  at this point. */
public void ejbActivate() {}

/** This method is invoked just prior to disassociating the object from
  the bean. The state of the abstract data model has already been
  synchronized with the database. We should release any object-specific
  resources as this point. */
public void ejbPassivate() { }
v041102                          Entity Beans                               42
           Implement Bean Class                                           Enterprise
                                                                               Java



      Database Synchronization Methods
/**
  This method is called just after the abstract data model has been
  restored from the database. This method should prepare any transient
  variables for use by the business methods as this time. */
public void ejbLoad() { }

/**
  This method is called just before the abstract data model gets stored
  to the database. This method should prepare the abstract data model
  variables for their stored state. */
public void ejbStore() { }


v041102                          Entity Beans                                   43
           Create Deployment Descriptor                                         Enterprise
                                                                                     Java



                   (ejb-jar.xml)
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans
     2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
<ejb-jar>
 <enterprise-beans>
  <entity>
    <ejb-name>BookCMP</ejb-name>
   ...
</entity>
 </enterprise-beans>

 <assembly-descriptor>
  <container-transaction>
    ...
  </container-transaction>
</ejb-jar>

v041102                             Entity Beans                                      44
                                                               Enterprise
                                                                    Java

          Define the Individual Beans
<entity>
  <ejb-name>BookCMP</ejb-name>
  <home>corej2ee.examples.entitybooks.ejb.BookRemoteHome</home>
  <remote>corej2ee.examples.entitybooks.ejb.BookRemote</remote>
  <local-home> corej2ee.examples.entitybooks.ejb.BookLocalHome
  </local-home>
  <local> corej2ee.examples.entitybooks.ejb. BookLocal</local>
  <ejb-class>corej2ee.examples.entitybooks.ejb.BookEJB</ejb-class>




v041102                      Entity Beans                            45
                                                        Enterprise
                                                             Java

          Define the Primary Key Class
    <persistence-type>Container</persistence-type>
    <prim-key-class>java.lang.String</prim-key-class>
    <reentrant>False</reentrant>




v041102                        Entity Beans                   46
          Define the Container Managed                   Enterprise
                                                              Java



                  Fields (CMP)
     <abstract-schema-name>Book</abstract-schema-name>
     <cmp-field>
      <field-name>author</field-name>
     </cmp-field>
     <cmp-field>
      <field-name>id</field-name>
     </cmp-field>
     <cmp-field>
      <field-name>title</field-name>
     </cmp-field>
     <cmp-field>
      <field-name>topic</field-name>
     </cmp-field>
     <primkey-field>id</primkey-field>
v041102                         Entity Beans                   47
                                                              Enterprise
                                                                   Java

          Define Environment Properties
  <!-- env-entry - lists properties that will be placed in the
       bean's environment at run-time.
       -->
    <env-entry>
      <description>This is a sample env entry.</description>
      <env-entry-name>example</env-entry-name>
      <env-entry-type>java.lang.String</env-entry-type>
      <env-entry-value>Sample Environment Value</env-entry-value>
    </env-entry>




v041102                      Entity Beans                           48
                                                        Enterprise
                                                             Java

                 Define EJB References
     <ejb-ref>
       <ejb-ref-name></ejb-ref-name>
       <ejb-ref-type>Session or Entity</ejb-ref-type>
       <home></home>
       <remote></remote>
       <ejb-link></ejb-link>
    </ejb-ref>
     <ejb-local-ref>
       <ejb-ref-name></ejb-ref-name>
       <ejb-ref-type>Session or Entity</ejb-ref-type>
       <local-home></local-home>
       <local></local>
       <ejb-link></ejb-link>
    </ejb-local-ref>
v041102                           Entity Beans                49
                                                      Enterprise
                                                           Java

          Define Queries CMP Queries
<query>
 <query-method>
  <method-name>findAll</method-name>
              <!— declared in BookLocal/RemoteHome
  <method-params>
  </method-params>
 </query-method>
 <ejb-ql>SELECT OBJECT(b) FROM Book b</ejb-ql>
</query>




v041102                    Entity Beans                     50
                                                                     Enterprise
                                                                          Java

                 Define Client Jar File
<!-- ejb-client-jar
    Specifies the jar file that contains classes for use by remote
  clients of the component.
  -->
  <ejb-client-jar>entityBooksEJBClient.jar </ejb-client-jar>
</ejb-jar>




v041102                          Entity Beans                              51
                                        Enterprise


          Things We Skipped (coming…)
                                             Java




• Defining Security Roles
• Defining Security Access
• Defining Transaction Scope




v041102              Entity Beans             52
    Defining Database-Specific Mapping                                              Enterprise
                                                                                         Java



      (weblogic-cmp-rdbms-jar.xml)
<!DOCTYPE weblogic-rdbms-jar PUBLIC
     '-//BEA Systems, Inc.//DTD WebLogic 7.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>BookCMP</ejb-name>
  <data-source-name>corej2ee/jdbc/DS</data-source-name>
  <table-map>
    <table-name>entityBooks_Book</table-name>
...
    <field-map>
    </field-map>
  </table-map>
 </weblogic-rdbms-bean>
 <create-default-dbms-tables>True</create-default-dbms-tables>
</weblogic-rdbms-jar>
v041102                               Entity Beans                                        53
             Map Columns to Fields              Enterprise
                                                     Java



          (weblogic-cmp-rdbms-jar.xml)
 <field-map>
   <cmp-field>author</cmp-field>
   <dbms-column>author</dbms-column>
 </field-map>
 <field-map>
   <cmp-field>id</cmp-field>
   <dbms-column>id</dbms-column>
 </field-map>
 <field-map>
   <cmp-field>title</cmp-field>
   <dbms-column>title</dbms-column>
 </field-map>
 <field-map>
   <cmp-field>topic</cmp-field>
   <dbms-column>topic</dbms-column>
 </field-map>
v041102                          Entity Beans         54
       Map Container-Specific Resources                               Enterprise
                                                                           Java



            (weblogic-ejb-jar.xml)
<!DOCTYPE weblogic-ejb-jar PUBLIC
     "-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB//EN”
     "http://www.bea.com/servers/wls700/dtd/weblogic-ejb-jar.dtd" >
<weblogic-ejb-jar>
  <weblogic-enterprise-bean>
    <ejb-name>BookCMP</ejb-name>
    <entity-descriptor>
...
    </entity-descriptor>

  <local-jndi-name>corej2ee/examples/entitybooks/BookCMPLocalHome
  </local-jndi-name>
 </weblogic-enterprise-bean>
</weblogic-ejb-jar>



v041102                                Entity Beans                         55
      Map Container-Specific Resources                             Enterprise
                                                                        Java



           (weblogic-ejb-jar.xml)
 <entity-descriptor>
  <persistence>
   <persistence-use>
     <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-use>
  </persistence>
 </entity-descriptor>




v041102                        Entity Beans                              56
                                                                 Enterprise
                                                                      Java

                JBoss (jbosscmp-jdbc.xml)
   <jbosscmp-jdbc>
     <defaults>
       <datasource>java:coredev/jdbc/DS</datasource>
       <datasource-mapping>Hypersonic SQL</datasource-mapping>
       <create-table>true</create-table>
       <remove-table>true</remove-table>
     </defaults>
     <enterprise-beans>
       <entity>
         <ejb-name>BookCMP</ejb-name>
         <table-name>entityBooks_Book</table-name>
         <cmp-field>
           <field-name>id</field-name>
           <column-name>id</column-name>
         </cmp-field>
         <cmp-field>
           <field-name>title</field-name>
           <column-name>title</column-name>
         </cmp-field>
         <cmp-field>
           <field-name>topic</field-name>
           <column-name>topic</column-name>
         </cmp-field>
       </entity>
     </enterprise-beans>
   </jbosscmp-jdbc>

v041102                                      Entity Beans              57
                                                          Enterprise
                                                               Java

            Database Synchronization
• As with all EJBs, only a single thread can be
  running within a bean instance
• Multiple entity bean instances can be created to
  represent same data in database
• Consistency ?
     – ejbLoad() and ejbStore() are called to synchronize bean
       with underlying storage




v041102                     Entity Beans                        58
                                      Enterprise
                                           Java

                  State Management
• State synchronization methods
     – ejbLoad
     – ejbStore
• Resource Management methods
     – ejbActivate
     – ejbPassivate




v041102                Entity Beans         59
                                                 Enterprise
                                                      Java

                     Entity Bean Types
• Bean can have total control over loading and
  storing from database
     – Bean Managed Persistence (BMP)
• Container can take over this responsibility
     – Container Managed Persistence (CMP)
     – Specialized Implementations
          • Toplink for relational databases
          • CICS




v041102                          Entity Beans          60
                                                        Enterprise
                                                             Java

                   CMP Summary
• Eliminates a lot of code
     – less code means fewer bugs
• Provides support for relationships (covered later)
• Provides support for database-generic queries
  (EJB-QL covered later)
• Problems
     – abstract model based on Java; database
       implementations do not always map Java constructs the
       same

v041102                    Entity Beans                       61
                                     Enterprise
                                          Java




          Bean Managed Persistence

                     BMP




v041102            Entity Beans            62
                                              Enterprise
                                                   Java

          Bean Managed Persistence (BMP)
• The BookBMPBean uses BMP
     – implemented all database interaction
     – create, remove, and find
• Have to do object-relational mapping
• Synchronize bean state with database when
  requested by container




v041102                     Entity Beans            63
                                                 Enterprise
                                                      Java

          Activation and Passivation
• When Passivated, bean should give up any
  resources held on behalf of the data represented by
  the Primary Key
• When Activated, bean can acquire and resources
  specific to the Primary Key




v041102                Entity Beans                    64
                                                Enterprise
                                                     Java

                    BMP Summary
• Have to handle all database interaction
     – except transactions
• ejbLoad() and ejbStore() called when bean
  instance state must be synchronized with database
• ejbActivate() and ejbPassivate() called when bean
  is moved between the ready state and pooled state




v041102                      Entity Beans             65
                                             Enterprise
                                                  Java

          Implement a BMP Entity Bean
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
…

public class BookBMP extends BookEJB {
 private DataSource dataSource_;
 private EntityContext ctx_;




v041102                       Entity Beans         66
                                                                     Enterprise
                                                                          Java

     Implement the Abstract Data Model
 private String id_;
 private String title_;
 private String author_;
 private String topic_;

 public void setId(String id)          { id_ = id; }
 public String getId()              { return id_; }
 public void setAuthor(String author)        { author_ = author; }
 public String getAuthor()             { return author_; }
 public void setTitle(String title)     { title_ = title; }
 public String getTitle()            { return title_; }
 public void setTopic(String topic)        { topic_ = topic; }
 public String getTopic()             { return topic_; }

v041102                              Entity Beans                          67
                                                                        Enterprise
                                                                             Java

                   Locate the Database
public void setEntityContext(EntityContext ctx) {
  super.setEntityContext(ctx);
  ctx_ = ctx;
  InitialContext jndi = null;
  try {
    jndi = new InitialContext();
    dataSource_ = (DataSource)jndi.lookup("java:comp/env/jdbc/mydb");
  }
  catch (NamingException ex) {
    throw new EJBException(ex);
  }
  finally {
    try { if (jndi!=null) jndi.close(); } catch (Exception e) {}
  }
v041102
}                                       Entity Beans                          68
                                                                             Enterprise
                                                                                  Java

                 Implement DB Insertion
public String ejbCreate(String id, String title, String author, String topic) {
  super.ejbCreate(id, title, author, topic);
  Connection conn = null;        PreparedStatement pstatement = null;
  try {
    conn = dataSource_.getConnection();
    pstatement=conn.prepareStatement("insert into Book (id, title, author, topic)"+
      ” values (?, ?, ?, ?)");
    pstatement.setString(1,id_);         pstatement.setString(2,title_);
    pstatement.setString(3,author_); pstatement.setString(4,topic_);
    pstatement.execute();                return id_;
  }
  catch(SQLException ex) { throw new EJBException(ex); }
  finally { … }
}
v041102                             Entity Beans                                   69
                                                            Enterprise
                                                                 Java

                  Implement PostCreate
public void ejbPostCreate(
  String id, String title, String author, String topic) {
  super.ejbPostCreate(id, title, author, topic);
}




v041102                            Entity Beans                   70
                                                                         Enterprise
                                                                              Java

                      Implement DB Load
public void ejbLoad() {
  Connection conn = null;
PreparedStatement pstatement = null;
  ResultSet rs = null;
  try {
    conn = dataSource_.getConnection();
    pstatement = conn.prepareStatement(
       "select id, title, author, topic from Book " + "where id = ?");
    pstatement.setString(1, (String)ctx_.getPrimaryKey());
    rs = pstatement.executeQuery();
    if (rs.next()) {
       ...


v041102                               Entity Beans                             71
                                                                                 Enterprise
                                                                                      Java

             Implement DB Load (cont.)
  if (rs.next()) {
      id_ = rs.getString("id");     title_ = rs.getString("title");
       author_ = rs.getString("author");       topic_ = rs.getString("topic");
       super.ejbLoad();
    }
    else {
       throw new EJBException("unable to locate row");
    }
 }
 catch(SQLException ex) {
    throw new EJBException(getText(ex));
 }
 finally { … }

v041102                               Entity Beans                                     72
                                                                         Enterprise
                                                                              Java

                    Implement DB Store
public void ejbStore() {
  Connection conn = null; PreparedStatement pstatement = null;
  try {
    super.ejbStore();
    conn = dataSource_.getConnection();
    pstatement = conn.prepareStatement(
      "update Book set title=?, author=?, topic=? " + "where id = ?");
    pstatement.setString(1,title_); pstatement.setString(2,author_);
    pstatement.setString(3,topic_); pstatement.setString(4,id_);
    pstatement.executeUpdate();
  }
  catch(SQLException ex) { throw new EJBException(getText(ex)); }
  finally { … }
}
v041102                             Entity Beans                               73
                                                                          Enterprise
                                                                               Java

                Implement DB Remove
public void ejbRemove() {
  Connection conn = null;
  PreparedStatement pstatement = null;
  try {
    super.ejbRemove();
    conn = dataSource_.getConnection();
    pstatement = conn.prepareStatement("delete from Book " + "where id = ?");
    pstatement.setString(1, (String)ctx_.getPrimaryKey());
    pstatement.executeUpdate();
  }
  catch(SQLException ex) { throw new EJBException(getText(ex)); }
  finally { … }
}

v041102                            Entity Beans                                 74
                                                                           Enterprise
                                                                                Java

                     Implement Finders
public String ejbFindByPrimaryKey(String pk) throws FinderException {
  Connection conn = null;          PreparedStatement pstatement = null;
  ResultSet rs = null;
  try {
    conn = dataSource_.getConnection();
    pstatement = conn.prepareStatement("select id from Book " + "where id = ?");
    pstatement.setString(1, pk);
    rs = pstatement.executeQuery();
    if (rs.next()) { return rs.getString("id"); }
    else { throw new ObjectNotFoundException(pk + " no found"); }
  }
  catch(SQLException ex) { throw new EJBException(getText(ex)); }
  finally {... }
}
v041102                            Entity Beans                                  75
                                                                   Enterprise
                                                                        Java

              Implement Finders (cont.)
public Collection ejbFindAll() throws FinderException {
  Connection conn = null;
  PreparedStatement pstatement = null;
  ResultSet rs = null;
  try {
    Vector pKeys = new Vector();
    conn = dataSource_.getConnection();
    pstatement = conn.prepareStatement("select id from Book ");
    rs = pstatement.executeQuery();
    while (rs.next()) {    pKeys.add(rs.getString("id")); }
    return pKeys;
  }
  catch(SQLException ex) {throw new EJBException(getText(ex)); }
  finally {... }
v041102
}                                   Entity Beans                         76
      Configure Deployment Descriptors                             Enterprise
                                                                        Java



                (ejb-jar.xml)
<entity>
  <ejb-name>BookBMP</ejb-name>
  <local-home>corej2ee.examples.entitybooks.ejb.BookLocalHome</local-home>
  <local>corej2ee.examples.entitybooks.ejb.BookLocal</local>
  <ejb-class>corej2ee.examples.entitybooks.ejb.BookBMP</ejb-class>
  <persistence-type>Bean</persistence-type>
  <prim-key-class>java.lang.String</prim-key-class>
  <reentrant>False</reentrant>
  <resource-ref>
   <res-ref-name>jdbc/mydb</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
  </resource-ref>
 </entity>




v041102                          Entity Beans                            77
      Configure Deployment Descriptors                             Enterprise
                                                                        Java



           (weblogic-ejb-jar.xml)
      <weblogic-enterprise-bean>
       <ejb-name>BookBMP</ejb-name>
       <reference-descriptor>
        <resource-description>
          <res-ref-name>jdbc/mydb</res-ref-name>
          <jndi-name>corej2ee/jdbc/DS</jndi-name>
        </resource-description>
       </reference-descriptor>
       <local-jndi-name>corej2ee/examples/entitybooks/BookBMPLocalHome
       </local-jndi-name>
      </weblogic-enterprise-bean>




v041102                         Entity Beans                             78
                                                      Enterprise
                                                           Java

                           jboss.xml
<entity>
  <ejb-name>BookBMP</ejb-name>
  <local-jndi-name>
     corej2ee/examples/entitybooks/BookBMPLocalHome
  </local-jndi-name>
  <resource-ref>
     <res-ref-name>jdbc/mydb</res-ref-name>
     <jndi-name>java:coredev/jdbc/DS</jndi-name>
  </resource-ref>
</entity>




v041102                         Entity Beans                79
                                           Enterprise
                                                Java




          Entity Bean Performance Issues




v041102               Entity Beans               80
                                                           Enterprise
                                                                Java

                 Performance Issues
• When could Entity Beans be expensive
    – CMP performs eager database synchronization on each
      transaction (EJB 2.0 abstract schema much better)
    – BMP allows for lazy database synchronization
• Who should call the Entity Bean’s Remote
  methods ?
• Should you utilize entity beans at all ?
    – Performance hit - all calls go through the container via
      the EJBObject
    – Higher performance going directly to the databases vs.
      functionality of container

v041102                     Entity Beans                         81
                                                       Enterprise
                                                            Java

               Entity Bean Summary
•   Models persistent state in database
•   Facilitates declarative persistence
•   BMP vs. CMP
•   Performance implications
     – wrap calls to entity beans with session beans




v041102                     Entity Beans                     82

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:3
posted:5/6/2012
language:
pages:82