Enterprise JavaBeans
Peter Komisar © Conestoga College  version 1.0  Fall / 2007

Reference:  Third Draft Document for Review, Sept. 17,2007,
SG24-7501-00 'Rational Application Developer V7 Programming
Guide'.


This is a synopsis of information found in the  the 16th chapter,
'Developing Web Applications with EJBs'  found in the third draft
Document for Review, dated October 23, SG24-7501-00 Rational
Application Developer V7 Programming Guide. It has been
prepared for private academic purposes and is not an effort to
publish the contained material.

Any anonymous quotes are from the above noted reference. 

Chapter 16 of the draft describes Enterprise JavaBeans (EJB)
demonstrating how to create, maintain, and test them in a J2EE
environment. Entity and session beans are integrated with the
earlier developed Web application.

Chapter Topics

Overview

Introduced in late 1999, the EJB technology has gained
momentum primarily because EJBs simplify developing
robust business components.

EJB Strengths
EJBs provide 'method-level security', where users or groups
can be granted or denied execution rights to any bean or method.

EJBs provide distribution capabilities to your application
allowing for scaling at the enterprise level. System modules
can be deployed to many different physical machines and
many separate OS processes optimizing performance,
scalability, and availability.

Persistence is preserving state, the values of its non-transient
variables even after the system that created that object has
stopped. Usually state is stored in a relational database.
 
However, the object-oriented (OO) and relational paradigms
differ a lot.
 
Relational models do not provide a way to represent behavior,
encapsulation, or complex relationships like inheritance. As well,
SQL data types do not exactly match Java data types, leading to
conversion problems. This 'impedance mismatch' is solved 'behind
the scenes' when using EJBs.


"Enterprise beans support multiple concurrent transactions with
commit and rollback capabilities across multiple data sources in
a full two-phase commit-capable environment for distributed
transactions."
The "24-7" nature of the Web has also made uptime crucial.
However, not every system needs to be designed for 24x7
operation handling millions of concurrent users.

Scalability should be achievable without sacrificing ease of
development, or standardization.

WebSphere  EJB support for scalability includes:
// No changes to the code are needed to use these features
A perceived business advantage is platform and vendor independence.
Because EJB architecture is an industry standard portability is achievable.
with J2EE applications being deployable on any J2EE compliant application
server.

A Down Side

Mentioned in class, EJB suffer from a  performance overhead
associated with making a network call. The ability to make a
local call on EJBs, a facility added in EJB 2.0, has provided a
way of escaping this performance hit.

EJB 2.0 adds Local Calls

"One of the most common complaints about EJB architectures
is that they are too resource-intensive, both in terms of memory
consumption and response time. . . . The EJB 2.0 spec . . .
does . .  provide a means of reducing the response time for a
request that involves interaction between multiple beans within
the same container.
The 1.0 and 1.1 specifications defined only one way to reference
one enterprise bean from another—through the bean's remote
interface. If both beans are in the same container, then this
network round-trip is unnecessary. The 2.0 specification defines
a new type of enterprise bean reference to avoid this problem—
the local reference."

-
Kyle Gabhart, How to Utilize EJB 2.0 Local References

http://www.devx.com/getHelpOn/10MinuteSolution/16677/1954?pf=true




EJB Architecture


EJB architecture reduces the complexity of developing business
components by providing support system level services, allowing
developers to concentrate developing business logic.

// See Fig 16-1

EJB Architectural Components

EJB Server

An EJB server is the part of an application server that hosts
EJB containers. It is also known as an EJS or Enterprise
Java Server. WebSphere Application Server is an example
of an EJS.

The EJB server provides the common services available
to all EJBs. The EJB server hides the complexities associated
with these services from the component requiring them. The
EJB specification outlines eight services that the EJB server
must provide:


J2EE Specified EJS Services
Because J2EE doesn't specify which of the Server or the
Container takes on these responsibilities, they are restated
below with detail in the context of the EJB container.



The EJB Container

"
The container hosts and manages an enterprise bean in
the same manner that the Java Web Server hosts a servlet
or an HTML browser hosts a Java applet."  

     - Monson-Haefel, jGuru: Enterprise JavaBeans Fundamentals

The EJB container
"Containers are transparent to the client in that there is
no client API to manipulate the container." A client doesn't
know in which container an enterprise bean is deployed.

The container supplies remote accessibility enabling remote
invocation of a native component over a network. EJB containers
use the Java RMI interfaces to allow clients to access EJBs.


Container /Server Responsibilities In Detail
// these are 'musts' to be J2EE compliant


EJB Components

EJB components are the Enterprise JavaBeans.They
are collectively made up from classes, interfaces and
instances. The IBM Redbook breaks EJBs down to
include the following sub-elements.

EJB Sub-Components

EJB Types

There are three types of enterprise beans: entity,
session, and message-driven beans.

Entity beans
// the nouns of the system, customer, account etc
// hold data

Entity beans represent the active objects of the
system. IBM calls them 'business or domain specific
concepts'). Common examples are customer and
account. Entity beans are persistent and maintain
state from call to call and across server restarts.

Entity beans usually represent data stored in a database.
The container determines when an entity bean is stored.
How the bean is stored can be through container-managed
persistence (CMP), or through bean-managed persistence
(BMP). Container-managed persistence is maps entity
bean fields to columns in a relational database accessed
by the EJB server.

Session Beans  // task oriented

A session bean encapsulate system tasks, and is often
used to implement facades for EJB modules. Usually
session beans are not persistent. (The Redbook calls
them 'conversational').

Session beans may be stateless or stateful. Stateless beans
have no 'conversational state', and are pooled for reuse.
Stateful beans track state on specific clients thus are not
sharable among clients.

Message-driven Beans (MDB)

 Message-driven beans may also be modeled to
perform tasks, however, they are invoked asynchronously
The bean either listens for or subscribes to messages
that are sent to it.

Entity and session beans are accessed synchronously
either through a remote or local EJB interface method
call. // synchronous invocation

An EJB client may make a remote call via a servlet,
or a local call such as when one EJB calls on another
EJB in same Java Virtual Machine.

Message-driven beans have their own call mechanism
and are not accessed through remote or a local interfaces.
MDBs are accessed solely through a JMS message. The
JMS architecture intercepts the message. The container
then delegates the message to a suitable MDB instance.


XDoclet Enterprise JavaBean


You will see in Eclipse menu items for XDoclet EJBs. The
following table has some information regarding this new
approach to creating EJBs.


<ejbdoclet/> Task

reference: http://xdoclet.sourceforge.net/olddocs/ejbdoclet.html

"This (Ant*) task allows you to generate various EJB-related files using nested subtasks and template files."

"You no longer view EJBeans as a bunch of interfaces and deployment descriptor files. You simply program your component and ejbdoclet does the rest, from generating component and home interfaces to deployment descriptor. The point is that you program your component and specify its meta-data in a per component fashion, you don't have to deal with monolithic ejb-jar.xml files, you set the deployment meta-data per component. You don't have to worry about outdating deployment meta-data whenever you touch the code. The deployment meta-data is continuously integrated. And the whole process is, in its nature, round-trip."

*" Ant is an [Apache] build tool for putting together the pieces of a program"          - Whatis.com

// popularized I think in the Apache, JBoss World of J2EE.




EJB interfaces and Classes


An EJB component consists of the following:
// depending on the bean type
// "Beans willing to be notified of timer events must implement the
// javax.ejb.TimedObject,
so that the container may call the
bean back when a timer expires."
 

EJB Client View


A client  needs a view to message an EJB component. A
view is a client interface to the bean, and may be local or
remote.
"Remote calls are more expensive than local calls."

"An EJB client may be a remote client, such as a servlet running
on another process, or may be a local client, such as another EJB
in the same container."

Generally a component exposes a local or a remote view but
not both. "EJBs that act as facades usually offer only a remote
interface while the rest of the components generally expose
only a local interface."

RMI Characteristics // RMI is at the heart of EJBS

"In remote invocation, method arguments and return values
are passed by value. This means that the complete objects,
including their non-transient reference graphs, have to be
serialized and sent over the network to the remote party,
which reconstructs them as new objects."

Object serialization and network overhead can be costly in
terms of response time.  However remote interfaces are
location independent so their methods may be called by a
client that is in or outside of the container.

 // remotes are available locally or remotely


Relationships in Relation to CMPs


Relations are a key aspect of object-oriented programming.
Complex networks can be created using these relationships.

CMP entity beans, whose state is managed by the container
are exampled in the various possible relationships.
There are three different types of relationships: // described in UML


Relationship Types

//  aggregation - a set of components instantiated outside
// another component then added to it via the latter components
// constructor.

// composition -  A set of components instantiated inside
// another component, and assuming no instances of the
// components exist in some other object.

// a strict composition is defined if the internal components
// are all inner classes

"It is the developer’s task to implement the differences
among the three kinds of relationships. These differences
may require considerations of characteristics, such as the
navigation of the relationship and the encapsulation of the
related objects."

 // build to suit the relationship specified

EJB query language (EJB QL)

The EJB query language is similar to SQL but
designed for querying  CMP entity beans. It is
used to utilize EJB custom finder or EJB select
methods in a portable way. EJB QL bases it
queries on entity bean schema types and so is
able to an object-oriented rather than relational
based query.

EJB QL Query Clauses

The bean provider defines the EJB QL queries in the
deployment descriptor.  "The SQL statements for the
actual database access is generated automatically by
the deployment tooling."


Example
// IBM Redbook

// a query that retrieves customers with large balance accounts

select object(c) from Customer c, in(c.accounts) a where a.balance > ?1

// Finder and select methods specified using EJB QL are
// portable to
any EJB 2.1 environment.



Coverage for the final test stops here. Good Luck!



Sample Application

Overview


The Redbook adapts the design developed in Chapter 7,
“Develop Java applications” The sample exercise doesn't
however depend on the sample from the Java application
chapter.

EJBs are used in the business model, replacing the
regular Java code used earlier. The rest of the design
still applies.


EJB Business Model

Session Bean - EJB Bank // session bean acts as facade
------------------------------------------------
Customer_*______*_Account
( many to many )

                     |  
                Transactions
               /            \
           Credit           Debit


// Customer, Account, Transactions, Credit and Debit are all entity beans




Description of the Architecture


The EJBBank session bean is the facade for the model.
Customer, Account, Transaction, Credit, and Debit are
implemented as CMP entity beans with local interfaces,
as opposed to regular JavaBeans.

As EJBs the entity beans all automatically gain:
However, this implies that the control and view layers will
not reference these entities directly as they will probably
be on different JVMs. Only the session bean (Bank) will
access the business entities through their local interfaces.

Remote interface exposures are limited to the facade
which acts as a gateway to the model. Too many remote
calls are not recommended because remote calls are
more 'expensive' than local ones. Also, having clients
access the model creates undesirable couplings and
dependencies.

// " Because the control layer is not able to reference the
// model objects directly, we reuse the Customer, Account,
// Transaction, Credit, and Debit from the Java application
// in Chapter 7, " ibm redbook pdf



Event Flow


Requirements to run the Sample


Enable Enterprise Developer Capability

Creating and Configuring an EJB Project

Enterprise JavaBeans and related Java resources are
created and stored in portable, modules within EJB projects.
The IDE has tools to facilitate the creation of all types of EJBs.
RAD 7 also supplies tools to define relationships, and create
resources such as access beans, converters, and composers.

A good pattern to use is a facade, made up of remote session
beans and and message-driven beans accessing a set of
business-logic components, either self-contained or associated
with external data sources.

Terminology for Java to SQL Translators
// from the IBM RAD 7 Redbook

" Converters and composers are used for non-standard relational
mapping. A converter allows you to transform a user-defined Java type to an SQL type back and forth. Composers are used when entity attributes have multi-column relational representations."



Steps For Creating the EJB Project

An EJB project and an EJB client project need to be created. The
client project holds the interfaces and classes needed by the client
to access the EJBs. Usually an enterprise application (EAR) project
is created to serve as a deployment vehicle for the EJB project.

Steps

// an existing project can also be selected
// from the drop-down combo box.


To create a new project and configure its location:
/*
"Note: The EJB client jar holds the home and component interfaces of the
enterprise beans, and other classes that these interfaces depend on, such as
their superclass's and implemented interfaces, the classes and interfaces
used as method parameters, results, and exceptions.

The EJB client jar can be deployed together with a client application that
accesses the EJBs. This results in a smaller client application as compared to
deploying the EJB project with the client application."  - IBM RAD 7 pdf
*/ 

If the project was not created from within the J2EE perspective
the user is prompted to switch to the J2EE  perspective which
should be done.

A Note from the IBM Redbook RAD 7 pdf
// error report until the EJB module contains an EJB

"Important: After creating the EJB project (RAD7EJB) you see an
error in the Problems view saying An EJB module must contain
one or more enterprise beans. An EJB project must contain at
least one enterprise bean. The error is corrected automatically
when we create an enterprise bean in the later steps."

Importing a Web and a Java project

The web front-end application developed earlier is reused. It 
was named RAD7EJBWeb.

To import the RAD7EJBWeb

Make the Java DTOs Available 

DTO - Data Transfer Objects

The RAD7EJBJava project is a trimmed version the
RAD7Java project developed in Chapter 7.  It uses
simple JavaBeans that are used as data transfer
objects (DTO) between the layers of the application.

The RAD7EJBJava project must be added to the EJB
project and the enterprise so the data objects and
exceptions defined in  the Java project can be referenced
from the EJB project.

The Java project continues to be the actual data model
of the sample application.

Configuring Dependencies

Setting up the Sample Database

The entity EJBs make use of the ITSOBank database.
A database connection is needed and is used by the
mapping tools to extract schema information from the
database.

// Reference: “Setting up the ITSOBANK database”,page 1314


Import the Physical Data Model


"We have to import the physical data model (database
schema) into the EJB project. This has to be done for the
mapping tools to be able to map the EJBs to the database
tables.


Importing the Data Model

You should see the database and tables imported into the
RAD7EJB project and a META-INF\backends\DERBY_V101_1
folder. // see diagram in pdf

Set up the Default CMP Data Source // container side

The EJB container must be configured to use the correct
data source.  The configuration is recorded in the deployment
descriptor for the RAD7EJB project.

Developing an EJB Application


To implement the ITSOBANK model  with EJBs, the entity
beans Customer, Account,  Transaction, Debit, and Credit
are created.

// see diagram  16.13 in the pdf


EJB Business Model    // brought forward from above

Session Bean - EJB Bank ( facade )
------------------------------------------------
Customer_*______*_Account
( many to many )

                     |  
                Transactions
               /   ( inheritance )  \
           Credit           Debit


// Customer, Account, Transactions, Credit and Debit are all entity beans



Creating the Entity beans

The ITSOBANK entity beans are defined in this section
in the following order:

Defining the Customer Bean
// only the XDoclet EJB was available in J2EE Eclipse

In the following dialog an CMP entity bean is created
called Customer, placed in the default package for this
EJB project section the skeleton of the Entity bean is created.
Note
build begins based on the Deployment Descriptor.
At this point we have this code built.

Important Point Re: Local

"According to best practices, entity beans should have only
local interfaces, so Local client view is selected by default."

This supports the notion that wherever possible, and generally
with respect to the data model, local rather than remote interfaces
should be used, to support more efficient processing.

Code So Far

package itso.rad7.bank.model.ejb;

class Customer
implements EntityBean{
 // with interface method stubs
}


Bean Build Continued

// Now fields that need to be container managed are specified
// Add the CMP attributes
Note On  Creating CMP attributes

You must define at least one key CMP attribute to create a
CMP entity bean.
For Customer Entity Bean the process is repeated for the
following fields.


Customer Entity Bean CMP Managed Fields
// from IBM RAD7 Redbook

Name
Type
Attribute Check box
ssn
java.lang.String Key field
title
java.lang.String Promote getter and setter
methods to local interface
firstName
java.lang.String Promote getter and setter
methods to local interface
lastName
java.lang.String Promote getter and setter
methods to local interface

// you may specify just 'String'

After closing the CMP Attribute dialog, the Enterprise Bean
Details page is shown.
A new UML class diagram is displayed showing the
Customer entity bean
// see figure 16-18

The Account and Transaction beans

The process is repeated for the Account and Transaction
Beans using the data described in the following tables.

Account Entity Bean CMP Managed Fields
// from IBM RAD7 Redbook

Name
Type
Attribute Check box
id
java.lang.String Key field
balance
 int Promote getter and setter
methods to local interface

Transaction Entity Bean CMP Managed Fields
// from IBM RAD7 Redbook

Name
Type
Attribute Check box
id
java.lang.String Key field
amount
 int Promote getter and setter
methods to local interface
timestamp
java.util.Date
Promote getter and setter
methods to local interface

// See the IBM RAD7 Pdf, page 748, for tips regarding
// ensuring that the id fields are unique


Defining the Credit and Debit Derived Beans


The Credit and Debit beans are slightly different as
they are derived. The procedure is the same except
that the superclass is specified. No additional attributes
are added.

// see the pdf for the Application Procedure if needed

// See Figure 16-20 for what is built so far

Creating the Entity Relationships

RAD streamlines the process of both creating and
maintaining CMRs or container managed relationships.
They can be created using the UML Diagram editor in
which case all the necessary code and deployment
descriptor changes are generated automatically.

Alternatively the deployment descriptor can be edited
directly. If this is done RAD also generates the
appropriate code changes.

Finally, you can also use the workbench menus to
accomplish the same task.

In the IBM Redbook pdf the first two strategies are
used.

Customer Account Association Relationship

Of interest in the UML visual editor approach is to
select, a many to many relationship from the palette
with the notation as follows which indicates any
number of objects to any number of objects.

UML Editor's 'Many to Many' Notation

0..*, 0..*

The action used in the UML approach is to right-click
over the Customer bean diagram and drag towards
the Account diagram, and then releasing the button
to install the relationship.

The  + symbol indicates visibility. Both objects see
each other, in other words, are separate objects.

// Double-click + customer and change to + customers.
// Double-click + account and change to + accounts.

The Account Transaction Composition Relationship

In the Transactions to Accounts relationship the default,
account, 0.. 1 for each bean, is modified to so the
transactions are 0 . . *, to create a one to many
relationship where one account might have many
transactions.

The many transactions are instances within an account.
Therefore, Account is not visible to Transactions. There
will be no plus symbol associated with the Transaction
diagram relationship. Also the Transaction object will
have a foreign key defined indicating it is part of a related
table in the database.

Methods Added as a Result of Defining the Relationships

The Account we have now these methods.

Account Class Methods Resulting from Relationship Definitions

Viewing the Account Bean

Notice aside from methods defined as a result of
declaring the relationships, the life cycle methods
are also stubbed in.

// see Fig. 16-27


Managing the Interfaces


To prevent clients from creating the Transaction EJB or modifying
it's fields any ejbCreate( )  methods in the remote and home interfaces
are removed. This make the transaction object seem immutable,
clients are blocked access to the constructor (create methods)
 and  the setter methods in the of the Transaction EJB. This is done
in the following procedure.

Demoting Methods Procedure

// setBalance from AccountBean is demoted
// the bean may need to be closed and opened to reflect
// the change in the Outline view

// ejbCreate, setAmount( ) and setTimestamp( ) from
// TransactionBean is demoted


Modify ejbCreate methods for Transaction, Credit, and Debit

"When creating a transaction object, we want to be able
to specify the transaction amount and let the bean generate
the identifier and timestamp automatically. Do the following
to accomplish this."             -ibm redbook RAD7 pdf

//The Java code for this section can be copied from the file
// c:\7501code\ejb\source\Transactions.jpage.


TransactionBean ejbCreate and ejbPostCreate
// from the ibm redbook RAD7 pdf

public java.lang.String ejbCreate(int amount)
   throws javax.ejb.CreateException {
       setId((new com.ibm.ejs.util.Uuid()).toString());
       setAmount(amount);
       setTimestamp(new java.util.Date());
       return null;
       }

public void ejbPostCreate(int amount)
    throws javax.ejb.CreateException {
    }



Adding Business Logic


While getter and setter methods are generated automatically,
business methods must be implemented manually.

This is as far as automated IDEs can take us. It doesn't
know what you are thinking with respect to business
operations!

The next two business logic methods are implemented.
Adding business logic to the Transaction bean


getTransactionType( ) Method


public String getTransactionType( )
throws itso.rad7.bank.exception.ITSOBankException {
    throw new itso.rad7.bank.exception.ITSOBankException(
       "Transaction.getTransactionType invoked!");
       }

In the parent no implementation is done other than
to support exception throwing. The method in the
parent is treated like an abstract method. It is in the
children classes, CreditBean and DebitBean, that
the methods get overridden and implemented.


Code Insert

/** Insert before the first method **/
public static final String TYPE_KEY = "Credit";
/** Update the getTransactionType method **/
public String getTransactionType() throws ITSOBankException {
return TYPE_KEY;
}

Omission I
 
The next three pages of the PDF show similar sorts of
business method implementations which are left to the
reader to check. We pick up again at the topic 'Creating
Custom Finders'.


Creating Custom Finders


"When you create an entity bean, you always get the
findByPrimaryKey finder
method on the home interface.
Sometimes, though, you have to find an entity based
on criteria other than just the primary key. For these
occasions, the EJB 2.1 specification provides a query
language called EJB QL. Custom finder methods are
declared in the home interface and defined in the EJB
deployment descriptor using the EJB QL."

Following is a procedure that defines a custom finder.

Account findAll query

To add the findAll query to the Account bean:
Opening the EJB deployment descriptor. On the Bean page,
by selecting Account and scrolling down to Queries, the findAll
query will be found.

You can also define and update queries in the deployment
descriptor.

// the process is repeated for the findByName query.


Object Relational Mapping


For the container to manage persistence, information must be
provided as to how the EJB fields are mapped to the relational
database. This information is stored in the deployment descriptor
and allows the container to manage database accesses on behalf
of the objects in the container.

" CMPs are abstract classes that associate to data, but do not
provide any implementation for accessing data themselves."

The advantages to separating the development and persistence

Aspect-Oriented Programming


"This is one of the fundamental axioms of 'aspect-oriented
programming', where the aspect of persistence can be
removed from the development process and applied later,
in this case at deployment time."


Mapping Strategies


Beginning with an object-oriented model, the environment
generates the data model automatically, including the
object-relational mapping and the DDL used to create
database tables.

Beginning with a data model, RAD generates the object
model automatically for you, including the creation of the
entity beans based on tables and columns that you select.
A commonly used compromise, where both existing object-
oriented and data models, are kept, creating a mapping
between the two, this is the approach used in the pdf example
where the ITSOBank database schema is used.


Omission II


For the sake of acheiving overall coverage of practical
aspects of EJB we leave it to the reader to investigate RAD's 
procedures for mapping between the object domain of the
entity beans and the database back-end.

// pages 765-770


Implementing the Session Facade


The next important component in the application architecture
is the session facade. Only the facade is visible to clients. The
entities are hidden behind the facade. This is the Bank session
bean.


Creating the EJBBank Session Bean


To create the session bean:
The default selection for a session bean is one supplied with
a 'remote' client view instead of a local client view. The IDE
knows that session beans are normally used to implement
facades that require remote access.
Adding Facade Methods
// source code in c:\7501code\ejb\source\EJBBankBean.jpage.

Next the facade methods that the client uses are added.
We look at one of it's method creations in detail.

Conversion // from IBM RAD7 Redbook

Integer versus BigDecimal: The database and the entity EJBs keep the balance and amounts as integers (int). The data transfer objects in the RAD7EJBJava project and in the Web front-end define the balance and amounts as BigDecimal. We have to convert between the two formats by dividing integer values and multiplying decimal values by one hundred.These conversions are done in the session facade (EJBBank) so that the view and the model are unaware of the difference.


Code to Add

import itso.rad7.bank.exception.*;
import itso.rad7.bank.model.*;
import itso.rad7.bank.model.ejb.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.math.BigDecimal;
import java.sql.Timestamp;

// after class EJBBank

// constant for conversion between int and BigDecimal
private static BigDecimal hundred = new BigDecimal(100);


Complete the getCustomer Method
// retrieves a customer by ssn:
getCustomer( ) Method Stub

public Customer getCustomer(String ssn)
throws InvalidCustomerException { }

For the moment, an error is reported: This method must
return a result of type Customer. To rectify:

Automatic Accompanying Environmental Changes

1 ) These action have led the environment to add a new EJB
reference to the Bank session bean. (This is visible in the
descriptor.) Also, the following line of code has been added.

Code Added

CustomerLocal aCustomerLocal =
find_CustomerLocalHome_findByPrimaryKey(ssn);

2 ) The following new local method has been added after
the last method of the class:

Local Method Added

protected CustomerLocal
find_CustomerLocalHome_findByPrimaryKey(String primaryKey) {

CustomerLocalHome aCustomerLocalHome = (CustomerLocalHome)
ServiceLocatorManager
.getLocalHome(STATIC_CustomerLocalHome_REF_NAME,
STATIC_CustomerLocalHome_CLASS);
try {
if (aCustomerLocalHome != null)
return aCustomerLocalHome.findByPrimaryKey(primaryKey);
} catch (javax.ejb.FinderException fe) {
// TODO Auto-generated catch block
fe.printStackTrace();
}
return null;
}


3 ) Several constants (and imports) have been added to the class:

... String STATIC_CustomerLocalHome_REF_NAME = "ejb/Customer";
... Class STATIC_CustomerLocalHome_CLASS = CustomerLocalHome.class;

4) The serviceLocatorMgr.jar has been added to the RAD7EJBEAR
Enterprise Application.

// contains the implementation of the ServiceLocatorManager class
// it is also added to the Java build path and the Java JAR Dependencies
// for the RAD7EJB project.

The Method is Modified to throw InvalidCustomerException

The find_CustomerLocalHome_findByPrimaryKey method is
modified, as shown below, so that an application-specific exception
is thrown when the customer cannot be found.


Added throws Clause for InvalidCustomerException
// from the IBM RAD7 Redbook

protected CustomerLocal find_CustomerLocalHome_findByPrimaryKey
(String primaryKey) throws InvalidCustomerException {
......
try {
if (aCustomerLocalHome != null)
return aCustomerLocalHome.findByPrimaryKey(primaryKey);
} catch (javax.ejb.FinderException fe) {
// Customer Home not found
throw new InvalidCustomerException(primaryKey);
} ......


The Completed getCustomer( ) Method

"The method uses the find_CustomerLocalHome_findByPrimaryKey
method to look up the customer in the database and then builds a
data transfer object and returns that to the caller."

The getCustomer( ) Method Implementation
// from the IBM RAD7 Redbook

public Customer getCustomer(String ssn) throws InvalidCustomerException{
CustomerLocal aCustomerLocal =
find_CustomerLocalHome_findByPrimaryKey(ssn);
Customer customer = new Customer(ssn, aCustomerLocal.getTitle(),
aCustomerLocal.getFirstName(), aCustomerLocal.getLastName());
return customer;
}


Omission III

The rest of the functions and business code are added in a
similar fashion on pages 776 to 780 of the pdf.


Generating the Deployed Code


Once the definitions of the EJBs are complete the deployed
code should be generated. Deployment of EJBs generates
many helper classes based on the mapping of the entity EJBs
to database tables.

To generate the deployed code:

Classes Generated


Testing EJBs with the Universal Test Client


Before integrating the EJB application with the Web application
the entity and session beans can be tested to ensure they are
working propertly. RAD7 supplies the Universal Test Client (UTC)
to do this.


Omission IV


We don't have time to look at this interesting section
where a server is started and individual methods are
inspected for their activities. We will gloss the actions
from the PDF from pages 781 to 787.


Adapting the Web Application


Now the model has to be changed on the web application
to use the EJB model with it's connection to the relational
database. The ITSOBank class is redirected to make calls
on the session facade bean, EJBBank.

The Bank interface is re-implemented to make calls on
the EJB model's entity beans. On page 789 to 791 some
of the restructured interface methods are shown.


Running the Web Application


Finally, the application is run, this time with the client
accesses data from the database via the EJB session
beans.

To run:


Assignment


No assignment. Good luck on the test. Note
I will not test on the mechanics of the bulleted
procedures.