Docstoc

ENTITY BEAN

Document Sample
ENTITY BEAN Powered By Docstoc
					DEVELOPING ENTERPRISE
APPLICATIONS USING EJB

    ENTITY BEAN
                  CONTENTS
•   Entity Beans
•   Container-Managed Persistence Beans (CMP)
•   Bean-Managed Persistence Beans (BMP)
•   Steps to develop CMP and BMP on NetBeans
•   Workshops
•   Exercises
                     ENTITY BEANS
• Enterprise Beans which represent persistent data stored in a storage
  medium, such as a relational database
• Persists across multiple sessions and can be accessed by multiple
  clients
• Acts as an intermediary between a client and a database
• Contain core business data and do not perform tasks such as workflow
  logic (Data modeling).
• Integrate with existing legacy enterprise application and can be reused
  as and when business process change.
• An Entity bean representing persistent data corresponds to a table in a
  database
• Each instance of the entity bean represent a row in the table
• EJB container creates instances of an entity bean and is responsible
  for loading data in an instance and storing the information (data)
  back into the database.
• The persistent mechanisms that enable you to perform these database
  manipulations, such as serialization, Object/Relationship (O/R)
  mapping to a relational database and support for JDBC are built-in the
  entity bean model
                CHARACTERISTICS
• Persistence
  –Implies that its state exists even after a client stops accessing an
   application
  –The persistent data remain intact even after the storage shuts down
• Shared Access
  –Multiple clients can share one entity bean by using separate
   instances of the entity bean
  –EJB Container maintains data consistency by synchronizing entity
   bean instances with the database
  –To maintain data consistency, the entity beans work within a
   transaction
• Primary Key
  –Each Entity bean has unique identifier; is known as Primary Key
   that enables the client to locate the exact entity bean
• Relationships
  –Like the data of a relational database, the entity beans are also
   related to each other
   ENTITY BEANS vs. SESSION BEANS
• Longevity
  – Entity beans have a longer life as compared to session
    beans that survives as long as it is being used by the
    client.
  – The EJB container removes them as persistent the
    settings. The entity beans exist as long as the data in the
    database that they represent exists.
  – Even if the database crashes, the entity beans get
    resurrected using the Entity bean code.
• Database
  – The DB and the entity beans are very tightly coupled.
  – The session beans however are not designed to closely
    integrate with the database.
  – The session beans can talk to the database only indirectly
    by using entity bean or a Java object using JDBC.
           TYPES OF ENTITY BEANS
• Container-Managed Persistence [CMP]
  – EJB Container performs persistence operations
  – Deployment Descriptor tells the container about the
    persistent fields and then container handles the data logic.
    (It is not necessary to write the JDBC code)
• Bean-Managed Persistence [BMP]
  – Programmer has to write the code for persistence
    operations
  – Entity Bean map themselves (coding) to a data store
    (Relation DB)
                                 CMP vs. BMP
EJB Container provides the persistence logic We need to write the persistence logic
We only need to maintain the business logic We need to maintain both data access
code                                        and business logic code
Reuse a CMP bean with different database Hard code logic required for different
by making minor modifications            database
EJB Container provides referential integrity   We need to provide the logic to
                                               implement referential integrity
                                               Performance: a well-written BMP offers
                                               better
                                               Flexibility: BMP also offers a lot more
                                               flexibility than CMP
Maintainability: easier to handle in CMP
because all these mapping information are
specified in the deployment descriptors
Convenience: CMP leads to less production
time and quicker time to market as a lot of
code is generated by the container
           LIFE CYCLE OF ENTITY BEANS
                       •Initially, the beans do not exist
                       •When the Application server initializes them, they move from
                       this stage to the Pooled stage




                                      •When the server is first started, several bean
                                      instances are created and placed in the pool.
                                      •A bean instance in the pooled state is not ties to
                                      particular data
                                      •At this stage, the beans are referred as passivated.
                                      The bean remains in this stage till the client does
                                      not make a request for it or the container does not
                                      activate it.

•The bean’s business methods can be invoked when the bean is
at the ready stage.
•It remains at this stage till the client calls its remove method
or the container passivates it if the bean has been lying idle for
sometimes
      ENTITY BEAN INSTANCES
• Container use a mechanism to transfer information
  between the DB and the java object by making use
  of two callback methods
  – ejbLoad()
  – ejbStore()
• The developer never calls these methods explicitly.
  Therefore, he does not worry about synchronizing
  the object with the underlying DB.
    POOLING ENTITY BEAN INSTANCES
               EJB Container/ Server

                                     Passivate
           Container need    Call
           more resource                             Store
                                     ejbStore()
Request                             ejbPassivate()   Load    DB
                            Call     Activate
          Container
          create bean
                                    ejbActivate()

                                    ejbLoad()

 •The container perform dynamically assigning the instance bean to
 handle a different client’s request
 •Instance of an Entity Bean is a recyclable object
 •Instances are assigned to clients randomly
                                      CMP
•   EJB Container manages persistence logic
•   EJB Container handle the connectivity between application and database
•   Database operations are executed behind the scenes
•   Reduces coding time because we don’t have to write any JDBC code
•   Enables to create database-independent code
•   The instances and fields of a CMP entity bean are mapped with a specific
    database such that a change in one is automatically reflected in the
    corresponding database object as well
•   EJB QL statements used to query and DDL operations with database
•   Change the persistence representation from object database to relational
    database without changing a data logic method
•   Data logic methods and persistence representation are defined separately
•   Use the file server instead of an RDBMS as the back end of a CMP
    application
•   The records are stored in the files and these files are stored in the file server
•   We can easily implement relationships between CMP Entity beans
•   Relationships refer to the association of one bean with another
•   EJB container handles the relationships between CMP Entity beans. This is
    known as Container-Managed Relationship (CMR)
                    BEAN CLASS
• All the CMP EJBs have to implement the javax.ejb.EntityBean
  interface
• The callback methods invoked on the bean by the container are
  defined by this interface.
• Container-managed Persistent Beans do not require the developer
  to provide data access logic.
• Container provides the implementation to map the bean instances
  from and to data storage.
• Bean class must declare abstract and public.
• Implement accessor methods (get – set of field)
• All of accessor methods must declare abstract.
• ejbFindByXxx need not implement in bean class. Instead of, define
  SQL statement in Deployment Descriptor.
• Implements the business methods of the bean
• Notes: No persistence field means that the fields that map to
  the data in the database are invisible in the abstract class
               CALL BACK METHODS
             Methods                             Implementation
                                    Access the context and to acquire the
setEntityContext(EntityContext ctx) environment information. The context has to
                                    be in a member variable.
                                   All    resources    allocated     during   the
unsetEntityContext()
                                   setEntityContext() have to be released.

                                   Create new data in the DB and initializes.
                                   Database representations have to be created
PrimaryKey ejbCreate(<…>)
                                   explicitly
                                   Return PrimaryKey for EJBHome/Container

                                   Once the bean instance is associated with the
ejbPostCreate(<…>)
                                   EJB Object, the ejbPostCreate() is called.
       CALL BACK METHODS (cont)
       Methods                         Implementation
                    Find primary key and assign to primary key attribute of
ejbActivate()
                    instance bean
ejbPassivate()      Assign primary key attribute of instance bean to NULL
                    Load data from DB – execute Select statement with
ejbLoad()
                    primary key parameter
                    The data in the database is explicitly updated through a
ejbStore()
                    storage API.
                    Destroy the data from the database – execute Delete
ejbRemove()
                    statement with primary key parameter
                    Once data is found, the primary keys for that data are
                    sent back to the container. The container will then
ejbFindByXxx(<…>)
                    create EJB objects and associate bean instances with the
                    objects. (not implement in CMP Bean)
                                    ejbCreate
• Used to initialize the fields of a bean instance which can be used for a particular
  client to create the underlying database data.
• The parameters vary with respect to the ejbCreate() method. Therefore, there are
  multiple ways to initialize an entity bean instance.
• The create() methods in the home interface have to be duplicated in the bean class.
• Optional
• Returned DataType of ejbCreate method is Primary Key

           Client                                  EJB Container/ Server
                        Call create()
                                          Home        Call ejbCreate()
                     Returns object       object
                                                              Entity bean
                                           Returns             instance




                                                                          database data
                                                                          Call ejbStore
                    Create EJB object      primary key




                                                         Insert results


                                                                            to create
                                           EJB
                   Call ejbPostCreate()   object
           flags
•
                                       ejbFindByXxx
    Find the existing entity bean in storage
•   All finder methods have to begin with “ejbFind”.
•   There has to be at least one finder method by the name ejbFindByPrimaryKey(). The method finds a unique entity bean
    instance based on the unique primary key.
•   The client will never call the finder methods on the bean instance itself
•   The finder method has to return the primary key for the entity bean it finds. Other than this, it can also give an
    enumeration of primary keys.
•   There can be various finder methods, with different names and different parameters.
•   The create() methods must define in the home interface



               Client                                          EJB Container/ Server
                          Call findByXXX()
                                                      Home        Call ejbFindByXXX()
                          Returns object              object
                                                                           Entity bean
                                                        Returns             instance




                                                                                       database data
                          Create EJB object             objects




                                                                      Call ejbLoad()

                                                                                          Find on
                                                       EJB
                        Call ejbPostCreate()          object
               flags



                Instance bean is not created
                               ejbRemove
• Called to remove data from the database.
• The instance of the bean can be recycled to handle data from a
  different database
• Does not take any parameters
• This method is not called if the clients time out. Server
                                       EJB Container/


                                         Home    Call ejbRemove()
                   Call remove()
          Client                         object
                                   Call ejbRemove() Entity bean
                                                       instance




                                                                     database data
                                                     Delete Result
                                         EJB




                                                                        Delete
                   Call remove()        object




         Release bean & destroy EJB Object
   setEntityContext & unsetEntityContext
   • Enterprise beans have a context object which identifies the bean’s
     environment.
   • Context objects are accessible to the beans in order to retrieve
     information, such as transaction and security information.
   • The interface to be used for entity beans is the
     javax.ejb.EntityContext.
   • This method is called before container creates the instance bean.
   • unsetEntityContext: disconnect between bean and enviroment
     (undeploy)
     Methods                                  Descriptions
getEJBObject()        Retrieve the EJBObject[Remote]associated with Entity Bean
getEJBLocalObject()   Returns the LOCAL [component] interface of an entity bean
                      Retrieve the primary key currently associated with the entity
                      bean instance
getPrimaryKey()       Should be call in ejbLoad & ejbRemove to provide
                      information the primary key that needs to be looked for or
                      removed
         REMOTE INTERFACE



             Remote Interface
             Invokes Methods
                 Business       Entity
Client           Method         Bean
                signatures
              HOME INTERFACE

                                    create
                                                  Entity Bean
                       Home                         Object
           Uses       Interface
                                    find
                                                  Entity Bean
Client                                              Object
                      Methods
                                   destroy
                                                  Entity Bean
                                                    Object



The home interface is used by the clients to create, find
and destroy entity bean objects.
                  LOCAL INTERFACE

                     EJB Container/ Server

                                          Local Clients

               Entity Bean    Invokes     Entity Bean/
                                          Session Bean/
                Methods                       MDB
                              exposes


                               Other
                             Enterprise
                               beans


Local Interface allows the beans to expose its methods to other beans
that reside within the same container (local clients).
      LOCAL HOME INTERFACE



Same as Home Interface which allows creating EJB
    Object instance that reside within the same
             container (local clients).
•
            PRIMARY KEY CLASSto come from the
    The fields present in the primary key class have
    container-managed fields of the entity bean class.
•   Optional because the developer can use Java Object Data Type. (if
    your key is made up of a simple data type such as Integer and
    String)
•   However, if the primary key is complex and contains multiple
    fields, then you definitely need to create the primary key class
•   DataType using in the Primary Key class similar to the field’s
    datatype in the bean class &̀ return datatype of ejbCreate
•   The primitive type can not use for Primary Key’s DataType
•   Rules of implementation Primary Key class:
    – Class must declare public and implements java.io.Serializable (The Primary
      key class has to be a serializable class)
    – Constructor of Class Primary Key must declare public
    – The public fields are from the bean class.
    – Implement hashcode() and equals(Object) method.
        DEPLOYMENT DESCRIPTOR
• ejb-jar.xml
<entity>
   ...
   <persistence-type>Container</persistence-type>
   ...
   <abstract-schema-name>schema name</abstract-schema-name>
   <cmp-field><field-name>field name</field-name></cmp-field>
   <cmp-field><field-name>...</field-name></cmp-field>
   <primkey-field>primary key field</primkey-field> (optional with Object class)
   <query>
          <query-method>
            <method-name>findByXxx</method-name>
               <method-params>
                 <method-param>dataType</method-param>
               </method-params>
          </query-method>
          <ejb-ql>
   <![CDATA[SELECT OBJECT(a) FROM schemaname AS a WHERE a.field=?1]]>
          </ejb-ql>
   </query>
</entity>
      DEPLOYMENT DESCRIPTOR
• Config DB connection file on Application Server
    – The <tên db>-ds.xml file must               be deployed
      JBoss_Home/server/default/deploy (the driver must be
      existed in lib directory)
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
 <local-tx-datasource>
  <jndi-name>reference name</jndi-name>
  <use-java-context>false</use-java-context>
  <connection-url>jdbc:odbc:RegisterName – DNS</connection-url>
  <driver-class>sun.jdbc.odbc.JdbcOdbcDriver</driver-class>
  <user-name>username</user-name>
  <password>password</password>
 </local-tx-datasource>
</datasources>
 DEPLOYMENT DESCRIPTOR (cont)
• jbosscmp-jdbc.xml
<jbosscmp-jdbc>
   <defaults>
        <datasource>reference name</datasource>
        <datasource-mapping>DBMS</datasource-mapping>
        <create-table>False/True</create-table>
   </defaults>

   <enterprise-beans>
        <entity>
                  <ejb-name>ejb name</ejb-name>
                  <table-name>table name</table-name>
                  <cmp-field>
                           <field-name>attr/ properties class</field-name>
                           <column-name>table column</column-name>
                  </cmp-field>
                  ...
        </entity>
   </enterprise-beans>
</jbosscmp-jdbc>
DEPLOYMENT DESCRIPTOR (cont)




  jboss.xml: similar to Session Bean
         LIFE CYCLE OF CMP                                          Container doesn’t need
                                                                    instance
 Client invoke method                         Start
                                                                      Client called remove()
Client called instance       Init instance
                                                      unsetEntityContext()
                         setEntityContext()                   ejbRemove()

             ejbHome                          Pooled               ejbFind()

Client called create()                                                      Client called finder

                                   Activate                            Client called method
           ejbCreate(arg)                         Passivate
                                  ejbActivate()                        on passivate
                                                  ejbStore()
                                  ejbLoad()
  ejbPostCreate(arg)                              ejbPassivate()      Client need more resrc


                                      instances               ejbStore()
                                                                             Container – Bean
                                                                             store DB (Sync)
                         BMP
• A BMP entity bean contains the code required for
  managing persistence of the entity bean
• The developer has to provide the implementation to map
  the bean instances (persistence operations) from and to
  storage
• Persistence operations include storing, loading, and
  searching data in a database
• The code for managing the relationships needs to be
  written at the time of bean development
• Database access API, such as JDBC and SQL/J can be
  used for writing the code to manage the persistence
• Entity beans that are defined by complex joins, a
  combination of different databases, or other resources,
  such as legacy systems are easier to implement with BMP
                        BEAN CLASS
•   Implement the javax.ejb.EntityBean Interface
•   implement all the container callback methods
•   The declaration need not be an abstract class.
•   All the values mapping to the table columns along with get
    and set methods, and the Finder methods are declared in the
    Bean class.
      DEPLOYMENT DESCRIPTOR
• ejb-jar.xml
   – The ejb-jar.xml file lists details of the classes and interfaces of
     the bean, and the type and name of the primary key
<entity>
       <ejb-name>name</ejb-name>
       <home>home interface</home>
       <remote>remote interface</remote>
       <local-home>local home interface</local-home>
       <local>local interface</local>
       <ejb-class>bean class</ejb-class>
       <persistence-type>Bean</persistence-type>
       <prim-key-class>primarykey class</prim-key-class>
       <primkey-field>primary key field</primkey-field>
</entity>
• jboss.xml: similar to Session Bean
OTHER COMPONENTS




   Similar to CMP
      CMP DEVELOPMENT PROCESS
• Requirement
  – JBoss 4.2.2 GA Application Server
  – The data source must be existed
• Step 1: Creating a new EJB Module/ Enterprise
  Application project
• Step 2: Creating CMP Bean mapping with table on
  Relation DB.
• Step 3: Mapping the JNDI, DB to beans
• Step 4: Creating the GUI application to consume
• Step 5: Building & Deploying the project on
  Application server
• Step 6: Running the client to test the EJB
                    Creating the Data Source
• Creating Data source uses ODBC (creating if it does not exist)
   – Administrative Tools\ Data source (ODBC)
   – Click System DSN tab



                                            Click Add Button




        Choose the SQL Server




                     Choose Finish Button
Creating the Data Source




                  Type the data source name



                  Type or choose the DB server name




                              Click Next button
Creating the Data Source




                Check SQL Server authentication to able to
                connect anywhere else computer




                 Type username and password


                 Click Next button
             Creating the Data Source
                             Check the checkbox, then choose the
                             appropriate DB




Click Next button




    Choose Finish Button
             Creating the Data Source




• Click “Test Data Source …” button (to test connection)
• Then, click Ok button
     Creating Driver in NetBeans Runtime
• Right click con JDBC-ODBC Bridge, click connect Using …




                                         •Replace <DB> to your registered
                                         data source name, then fill user
                                         name and password that is used to
                                         connect DB Server
                                         •Get dbo on “Select Schema” on
                                         Advanced tab


                                                      Click Ok button
Step 1: Creating a new EJB Module/ Enterprise Application project
• Create the Enterprise Application with Application Client Module
Step 2: Creating CMP Bean mapping with table on
                  Relation DB




• Choose the Enterprise in Categories
• Choose the “CMP Entity Beans from Database” in File Types
• Then, click Next Button
  Step 2: Creating CMP Bean mapping with table on
                    Relation DB




• In “Data Source”, click combo box, choose “New
  Data Source …”
Step 2: Creating CMP Bean mapping with table on
                  Relation DB
                             Type the JNDI name
                             Choose the registered Driver

                                      Click Ok button




                                • Choose the table,
                                  then click Add
                                  button.
                                • Last, click Next
                                  button
Step 2: Creating CMP Bean mapping with table on
                  Relation DB



                                      Type or choose the
                                      package name




                                      Click Finish button
Step 2: Creating CMP Bean mapping with table on
                  Relation DB
Step 2: Creating CMP Bean mapping with table on
                  Relation DB
Step 2: Creating CMP Bean mapping with table on
                  Relation DB
• jboss-ds.xml


                                   Named on
                                   application server as
                                   “java:jndi-name”
                                   when deploying
Step 2: Creating CMP Bean mapping with table on
            Relation DB – Bean class
Step 2: Creating CMP Bean mapping with table on
            Relation DB – LocalHome
Step 2: Creating CMP Bean mapping with table on
             Relation DB – Local …
      Step 3: Mapping the JNDI, DB to beans
• Mapping the jboss as the session bean




• Creating the jbosscmp-jdbc.xml in the Configuration
  Files to mapping bean and DB
      Step 3: Mapping the JNDI, DB to beans
• Modifying the jbosscmp-jdbc.xml as following
   Step 4: Creating the GUI application to consume
• Creating stateless bean to consume CMP because the
  CMP is local that cannot consume at client application.
• The business method including
Step 4: Creating the GUI application to consume
 Step 4: Creating the GUI application to consume
• Creating the GUI application




• Creating the reference to the EJB on the coding
• Then generating code for all buttons
   – Insert


   – Search
Step 4: Creating the GUI application to consume
– Update


– Delete



  Step 5: Building & Deploying the project on
               Application server
Step 6: Running
      BMP DEVELOPMENT PROCESS
• Requirement
  – JBoss 4.2.2 GA Application Server
  – The data source must be existed
• Step 1: Creating a new EJB Module/ Enterprise
  Application project
• Step 2: Creating Entity Bean using manual coding
  (BMP) on callback methods.
• Step 3: Mapping the JNDI, DB to beans (optional)
• Step 4: Creating the GUI application to consume
• Step 5: Building & Deploying the project on
  Application server
• Step 6: Running the client to test the EJB
              Step 1: Creating a new EJB project
                 Step 2: Creating Entity Bean
• Create the EntityBean




• Choose the Enterprise in Categories, then choose the “Entity Bean”
  in “File Types”. Click Next Button
Step 2: Creating Entity Bean
                                      Type the Bean Name


                                      Type or choose the
                                      package name

                                     Type or Browser the
                                     data type of Primary
                                     Key that assign to
              Check the Bean
                                     object
              option

              Click Local checkbox




                                      Click Finish button
               Step 2: Creating Entity Bean
• Implement the Bean class
  – Declare the two properties mapping with DB fields,
  – Then generate the accessor method (using encapsulation fields)


  – To public the method to remote interface, choose the right bulb on
    selected method, choose add local interface



  – Applying to getStudentName and setStudentName methods
             Step 2: Creating Entity Bean
– Generating the code as
             Step 2: Creating Entity Bean
– Generating the code as
             Step 2: Creating Entity Bean
– Generating the code as
             Step 2: Creating Entity Bean
– Generating the ejbCreate method as following
             Step 2: Creating Entity Bean
– Modifying the ejbFindByPrimaryKey method as following




  – Modifying the ejbRemove method as following
              Step 2: Creating Entity Bean
– Modifying the ejbActivate & ejbPassivate, ejbLoad, ejbStore method as
  following
            Step 2: Creating Entity Bean
– Generating the ejbFindByName (Add Finder Method)
Step 3: Mapping the JNDI, DB to beans (optional)
Step 4: Creating the GUI application to consume
Step 5: Building & Deploying the project on
Application server
Step 6: Running the client to test the EJB
Step 6: Running the client to test the EJB
           WORKSHOP ACTIVITIES




Building the EJB module with CMP and BMP on Java Sun Application Server
combining with SQL Server 2005
      WORKSHOP ACTIVITIES (cont)




Building the Data Model and Object Model, then creating the CMP Bean to deploy
Sun Application Server
                         EXERCISES
• Do it again all of demos, workshops, and the following exercises
  on JBoss Server
• Using CMP to write the programs that can do
   – Access the table User(userId – text, name – text, company – text,
     companyAddress – text, password – text, emailId – text) including
     findByPrimaryKey, Enumeration findByName, Collection findAll methods
   – Access the table Students(RollNo – varchar(3), name – varchar(38), course
     – varchar(25)) including findByPrimaryKey, Collection findByName and
     findAll methods
   – Access the table student(studentid – integer, name – varchar(40), mark –
     integer)
• Using BMP to write the programs that can do
   – Access the table Item(itemNo – long int, description – text, quantity – int,
     rate – double, type – text, reorderLevel – int) include findByPrimaryKey,
     Enumeration findByDescription, Collection findAll methods
   – Access the table Students(RollNo – text(3), name – text(38), course –
     text(25)) findByPrimaryKey, Collection findByName và findAll
• Notes: should be use with one more DBMS (e.g. Access – SQL
  Server)

				
DOCUMENT INFO
hkksew3563rd hkksew3563rd http://
About