| EJB:
Learn EJB, EJB 2.1 Building Web service transaction systems.. |
Updated Mar 10, 2003
|
Overview
Tutorials
Examples
Session Beans
Entity Beans
Transactions JTA, JTS New
EJB 2.0
EJB 2.1 New
Deployment Updated
EJB Clients
EJB Tools New
Automating builds, tests
Performance, practices and patterns New
Vendors Updated
Special Topics
Books References |
Software packages:
EJB 2.1
JavaDocs New
EJB
2.1 JSR 153 PFD
EJB 2.1 Download
and Spec New
Web
Services for J2EE 1.0 New
J2EE:
Related:
javax.naming javax.transaction
javax.transaction.xa
javax.jts
(and org.omg.*) |
See also:
Java Skyline: Enterprise
Java Skyline: Learn JNDI
Java Skyline: Web services
Sun: EJB FAQ
jGuru: EJB FAQ
Sun: J2EE Interest Archive |
|
Considering what they are, Enterprise JavaBeans are "easy".
As of EJB
2.0 they became even easier. And as of EJB 2.1 you can generate Web services
from EJBs. You could say EJBs are too easy. You can create EJBs using an IDE with just a few mouse clicks. What
could be easier?
A major value of EJBs is their contribution to a set of business standards.
EJBs enable scalable distributed transactions and connection to a vast array of Internet services - a modern version
of what mainframe transaction systems used to do. However, no matter how easy EJBs may look, you need to be discressionary
and careful about usign them.
Scalability and distributed services, the platform architecture for EJB
and J2EE have been a complex undertaking. And to understand how to write, integrate, and deploy EJBs, you need
to understand this platform architecture.
A complete application that
uses EJBs has numerous source files that must be coded in Java and in XML. Using J2EE enabled tools simplifies dealing
with all these source files. However, EJBs remain challenging. There are performance issues and there are different
vendor implementations
to deal with.
What are EJBs? The Enterprise
JavaBeans (EJB) platform is transaction server technology. EJBs enable transaction processing. You can use them
to control transactions across multiple transaction (XA compatible) platforms including both database systems,
and other enterprise processing systems.
Enterprise JavaBeans is a specification - not a product. EJBs define the way that J2EE vendors have decided to implement multi-platform
transaction processing and the transaction container. EJB is implemented a major focal point of Sun's J2EE (Java
2 Enterprise Edition).
- EJB provides scalable containers that you write on-line transaction oriented
applications in.
- The container automatically loads and schedules the EJB applications
- J2EE provides a deployment mechanism to load applications - this deployment
mechanism is a model for vendor specific mechanisms that are provided by each vendor.
What is J2EE? J2EE is
the combination of APIs and deployment tools that supports EJB and other server components. These libraries include:
JNDI, RMI, RMI/IIOP, JTA, JTS, and often JMS, JSP, and Servlet API.
Unlike EJB, J2EE is a product as well as a standard.
How does J2EE/EJB support distributed transactions? J2EE simplifies application building through the use of API "layers."
These layers and names provide transaction services while hiding its complexity.
J2EE/EJB supports distributed operation through "names." Each
service has a name. A database connection has a name. An EJB has a name. Even a connection pool has a name. You
define these names in special files called "deployment descriptors" in XML. In the program, you refer
to these names using JNDI.
In the J2EE architecture, Java Transaction Architecture (JTA) provides
transaction control and Java Transaction Services (JTS), provides compatibility with other transaction servers.
Java Transaction Services is Sun's transaction compatibility layer that conforms to and implements a set of industry
business processing standards including OMG OTS 1.1, XA, TX and CORBA compatibility. Java Transaction Architecture.
JTA specifies the architecture for transaction servers and defines the interfaces for containers and components
within this architecture. For an overview of J2EE see J2EE: not just a language anymore by Andy Patrizio
in Java-Pro, Mar 1999.
|
|
|
Overviews of Enterprise JavaBeans
|
J2EE and EJB A J2EE servers are also known
as a "container." J2EE divides the deployment into two separate containers with JSP and Servlets in one container and EJBs.
The container for EJBs is of course called the "EJB container," These containers can be run in separate
JVMs or in the same one.
Overview of EJBs There are several kinds
of EJBs:
- Session beans
are associated with a client with a simple session interface to process work. Session beans can be either stateful
or stateless.
- Entity beans
represent persistent entities in an external resources such as databases and other enterprise servers.
- Message driven beans. Java Message Service message services (JMS) initiate
a request to a message driven bean.
EJB Lifecycle The
container is responsible for loading, activating, and in general maintaining the "life-cycle" of objects
it provides. EJBs have a fairly complex life-cycle. Kevin Boone provides a good Overview of EJB lifecycles (The
K Zone).
|
How do you use an EJB? EJB clients are either
external or internal and as of EJB 2.0 separate interfaces are provided for external and internal clients. A client
connects to an Enterprise JavaBean by:
- Obtaining a reference to an EJBHome
- Obtaining a working reference to the bean. If the client is remote, it
uses a Remote interface.
If the client is inside the EJB container (such as another EJB) it can instead use a Local
interface.
- The developer must write the Bean and its Home interface, Remote interface
(and Local interface if there is one).
The above is true of both Session and Entity Beans.Message Driven Beans
(As of EJB 2.0) do not have a Home or Remote interface.
Highly recommended: The Enterprise JavaBeans books by Richard
Monson-Haefel, O'Reilly - the first version of which was written in June 1999. Richard has a very useful site called
JMiddleware.which has an EJB Links page.
Jeff Gallimore provides some guidelines and a nice overview of EJB methods and classes
Mark Johnson provides an overview of EJB 1.0 in this Beginners Guide to Enterprise JavaBeans,
JavaWorld Oct 1998.
Defunct: For a short
introduction to EJB see: The Enterprise JavaBean Model and
the rest of the JOnAS whitepaper from Bullsoft.
|
|
Tutorials
and links
|
***
Richard Monson-Haefel's EJB 2.1 Series on TheServerSide
starting with What's New in EJB 2.1 (eventually
to be published by O'Reilly) presents important changes in the EJB 2.1 spec with regard to Web services, message
driven beans, EJB QL, the timer service. Do not miss.
*** Enterprise
Beans section of "The J2EE Tutorial" by Dale Green (Sun)
discusses Web services and the Timer service and provides an example of an EJB Web service including creating and
deploying.
***:
Sun Java Developers Connection has published a 4-part tutorial called Writing Enterprise Applications for the J2EE Reference Implementation by Monica Pawlan.
***
An incredibly throrough tutorial and discussion see How to Build a Really Big Distributed J2EE System Using Tools You Have Around the
Office by The Advanced Application Architecture Team (GemStone:
Java Success), Feb 2000.
Kevin Boone (Sun UK) has a set of excellent tutorials called The K-Zone: EJB transactions and Beginning EJB programming using JBoss.
Also, Trivera Technologies lets you download this recently updated (Register) Developer's Guide to Understanding Enterprise JavaBeans™ 2.0.
Tutorials using Automated Tools. There is relatively complete tutorial
called The EJB Tutorial that uses the Bizzard, the EJB wizard from Blazix. See also Vendor section
(below). |
|
General links
|
The <ejb-link> page of EJB QL World and the EJB Links page (Volatanic.biz).
JDance: EJB |
|
Examples
|
"The Blueprint:" On
the Java Developers Connection, early access Sun provides an 266 page set of guidelines and example application
in Sun BluePrints Design
Guidelines for the Java 2 SDK, Enterprise Edition. Please note
that these are not necessarily best practice guidelines but instead they are a demonstration of what is possible
using EJB and J2EE
Ethan Henry provides an overview of the blueprint in Sun's BluePrints for J2EE, Feb 2000,
JavaWorld. Monica Pawlan has provided a BluePrint Digest and list of J2EE downloads and resources.
Richard Monson-Haefel provides some additional guidelines called EJBTips on EJBNow.
BEA provides a whole library of examples on numerous topics
including entity beans, session beans, bean communication, stateful sessions. |
|
Session Beans
|
Updated There
are two types of session beans: stateless and stateful. Within the EJB container, Stateless session beans generally
represent simple transactions. However, be aware you can use stateless session beans to serve as part of a complex
series of interactions where state is maintained elsewhere.
Stateful beans, as the name implies, store state within the bean - and
can store state for a somewhat extensive time. Once having connected to a stateful bean, the client keeps a reference
to the bean and surrenders it when finished by doing a remove.
Orion Server has a very simple introduction:Making your first Enterprise bean (a stateful session bean). For a detailed and thorough explaination see Gopalan Suresh Raj's Developing Session Beans on Web
Cornucopia. Michael Shoffner provided an early article called Write a session EJB in JavaWorld,
July 1998. Session beans can be very simple or quite complex. An instance of a stateful session bean is dedicated
to a single user. It stores at least one and possibly many variables within the bean while it is in use.
New Web
services. You can implement Web services in a stateless sesision
bean Note that state here refers only to the automated system - its "client-server" state. Web services
are geared to go beyond client-server. In a Web service application, you are in no way not prevented from storing
state in a database.
Implementing a shopping cart.
In the EJB world, the stateful session bean (SFSB) is a major way to implement a shopping cart. Always remember
there are other ways implement do this however. Depending on modeling requirements, the shopping cart SFSB and
purchase items can have very detailed or very simple set of attributes.
- Undepletables : An inventory item can be undepleteable if there is no
chance that the item is ever out of stock. A software program, video, or PDF file, or even a tee shirt with given
design that one can manufacture might be thought of as infinitely replicable.
- Finite objects - unshown quantity: All other objects are finite in nature.
However, you may not wish to reveal the quantity on hand to the purchaser. For instance, a book store may simply
note that an item usually "ships within two days" to indicate that it is generally available - or "ships
within a week" to indicate that it is less available and more in danger of being depleted.
- Finite objects - visible quantity: For a near one-of-a-kind item like
a certain vintage of wine you may wish to tell the purchaser exactly how many are available for purchase. Record
locking for this type of object is necessarily different. If a buyer elects to place a 1982 bottle of Latour in
the shopping cart, you will want to mark that item as unavailable in the database - until the cart has been abandonned
(timed out) or purchase completed.
As just hinted at, the state of the cart EJB will change at various shopping
junctures:
- Completing purchase. When the customer goes to check-out, this process
completes the transaction, makes required records, and moves resources accordingly.
- Abandonned carts. Depending on the type of inventory you are selling,
you may require certain processing for abandonned carts. The EJB model makes this possible by providing that specific
methods are called - for instance when a cart is destroyed.
- If the cart contains a rare item, you may wish to have the cart time out
sooner.
Cart examples. The J2EE
Blueprints provide one example of a shopping cart. Here is an annotate listing of Cart Bean from Sun. In the Sun example,
the cart model is implemented as a java.util.Collection.
For another example see Sun's iPlanet SOAP Shopping Cart Service
(SDC)
|
|
Entity Beans
|
Entity beans are often described as "the things that often represent
database elements" to your application.
Accessing an Entity Bean: An
entity bean could represent a permanant or inventory item used by the business. The user of an EB gains access
to it through the Home interface and through the EJB server (the container). The EJB container provides access
to an entity beans under "managed persistence." Managed persistence means that from an application programmers
point of view, you don't need to load the entity bean into memory. This is done for you -- either by the container,
via Container Managed Persistence (CMP), or by the entity bean itself using Bean Managed Persistence (BMP). Additionally,
each Entity Bean provides at least one "find" method -- a way for you to look it up when you need to
use it.
When you write an entity bean, you need to implement at least one "find" method. The remove method on
an entity bean destroys the bean - meaning (for database) it deletes the row in the database table. Entity beans
can also represent an entity in an external integrated system using the J2EE Connector Architecture.
The exersize tutorial on Sun: EJB Working with Entity and Session Beans
By Monica Pawlan develops a small application that uses entity beans. Gopalan Suresh Raj's Web Cornucopia explains
Developing
Entity Beans in depth. |
|
EJB 2.0
|
Updated The
EJB 2.0 specification contains a number of features. *** Enterprise JavaBeans in a Nutshell Richard
Monson-Haefel (JMiddleware) EJB 2.0 Impacts Next-Generation J2EE Servers
by Jonathan Maron and Greg Pavlik, Java Pro, Jan 2002. See also EJB 2 and J2EE Packaging O'Reilly,
Jun 2001, and EJB 2.0 articles (ZIP) by Tyler Jewel (BEA).
New features in EJB 2.0: |
| CMP 2.0 and Abstract Persistence |
In EJB 2.0, (CMP 2.0) you write a CMP entity bean as an interface that the
container implements. This greatly simplifies entity bean authoring. See Enterprise JavaBeans 2.0 Container-Managed Persistence Example by Beth Sterns, July 2001 (Sun) and OrionSupport's EJB 2.0 CMP entity bean
for an example. For a practicle example see Incremental J2EE by Vince Huston |
| EJB QL |
Additionally EJB 2.0/CMP 2.0 further simplifies entity bean writing. It enables
you to implemet finder methods without writing Java code. Instead you write WHERE/FROM queries in the ejb-jar.xml
file. For an EJB QL reference see EJB
QL World and it's <ejb-link> page. For an example
see BEA's Using
EJB QL. |
| Message Driven Beans: |
Message Driven Beans (MDBs) provide integration with JMS by processing JMS
messages. MDBs have no home or remote interface. For general information on MDBs, see BEA's Using Message Driven Beans. |
| Local interface |
The local interface provides the ability to encapsulate EJBs within an application.
Using the Local interface an EJB can only receive calls othe EJBs. For a brief intro on changing a Remote interface
to a Local, see Creating a Local Interface and Accessing a Bean Through It (DevX -10 minute solution). And see EJB 2.0: "Going Local" and Staying Remote
Rudy Dahbura (Java Pro) Aug 2002. Also general discussion Dynamic Proxy for Local and Remote Interface
Kjetil Helle, Aug 2001, TheServerSide. |
| |
Inheritance |
Importantly, EJBs (javax.ejb.EntityBean and SessionBean) are now interfaces
- making way for robust inheritence. This opens the door for EJB developers to use a much fuller range of the architectural
practices that are available to OOP. It also means better control of persistence by tools and that there are alternatives
and JDO is not as necessary as it once seemed. See Emmanuel Proulx (On Java) series Sep- through Jan 2003:
. EJB
Inheritance: Part 1 EJB inheritance - advantages in general
. Part
2, inheritence with Entity Beans
. Part
3 inheritence with Session Beans,and
. Part
4 inheritence with Message Driven Beans and JMS.
Also Inheritence
and EJB Danial O'Connor Jun 2002 (ServerSide), |
|
EJB 2.1
|
New The
EJB 2.1 specification provides a number of features and enhancements. Short overviews: A brief review of the EJB 2.1 specification
by Rahul Tyagi (Builder). See also Tarak Modi's What's New in EJB 2.1? (JavaPro,
Oct 2001). EJB 2.1 includes the following: |
| |
Web services |
EJB 2.1 provides the ability to deploy a stateless session bean as a Web service
end point and makes the EJB container accessible as a Web service implementation. See Dale Greens New Features in EJB 2.1 (Sun). |
| |
Timer service |
The timer service in the EJB 2.1 container enables scheduling of callback
actions to occur. The timer activates the EJBTimeout method. To access the Timer service use EJBContext. See EJB
2.1 the Timer Sevice by Richard Monson-Haefel (ServerSide) |
| |
EJB QL (upgrade) |
EJB QL now has aggregation functions to enable returning of a single value
- and "ORDER BY." See EJB 2.1 Adds New Funtionality to EJB QL
by Richard Monson Haefel (ServerSide). But it doesn't but not "GROUP BY" to return a collection (for
some reason). See especially the discussion on TSS for the same article. |
| |
Message Driven Bean (upgrade) |
Message Driven Beans now includes the ability to connect J2EE Connection Architecture
message services. See EJB 2.1: The enhanced Message Driven Bean
by Richard Monson Haefel (ServerSide) |
|
Deployment
Creating Deployments
|
New *** For a discussion of EJB 2.1 Implementation see Implementing
a Solution in EJB 2.1 from EJB 2.1 Kick Start by Peter Thaggard
(Sams)
Deployable EJBs are first placed into a deployment, and then the deployment
is deployed to the app server. For EJBs, a jar (Java Archive) serves as the vessle for deployment. Multiple jars
themselves may be placed in an ear (Enterprise Archive). Then the deployable jar or ear full of jars is deployed
to the app server. So deployment is actually two steps 1) creating the deployment vehicle (jar or jar and ear)
that contains the EJBs and their metadata and 2) Deploying the ear or jar to the app server.
What's in an EJB jar? First
let's focus on creating an EJB jar. The deployment jar must contain the following:
- The main directory:
- One or more application package directories that contain one or more EJBs.
Each EJB must contain
- EJB classes: Each EJB includes the EJB Home interface , Remote interface
(or Local interface), and the EJB bean itself
- Stub classes: For most App servers the jar also contains (RMIC or EJBC)
stub implementation files.
- A directory called META-INF: contains Deployment metadata files that describe
the EJBs. For each EJB there must be:
- ejb-jar.xml In ejb-jar.xml, you define the name of the EJB and what type
it is (session, stateful or not, entity, CMP or BMP).
- <appserver>.xml
where <appserver> signifys the name of an application server. For instance, to deploy to Weblogic, this file
is called "weblogic-ejb-jar.xml." For Oracle9iAS thi is a file called "orion-ejb-jar.xml."
- New Web
service information is located in the jar file in META-INF/webservices.xml. This file contains port name, QName,
class, endpoint interface, location of the WSDL definition, and the location of the JAX-RPC mapping file. See Web
Services for J2EE, Version 1.0 by Jim Knutsen and Heather Kreeger (IBM) Section
7. Deployment Descriptors (IBM)
- New The
JAX-RPC Mapping Deployment Descriptor file for Web services See same reference Section
7.3 (IBM)
- New If
the EJB application is a front-end for other Web services the deployment must contain a Web services client deployment
descripter file see same reference Section
7.2 (IBM)
The what and how of it:
The appserver and ejb-jar.xml files have slightly different purposes. ejb-jar.xml describes what EJBs are being deployed. The <appserver>.xml
ejb-jar.xml: Below are
re ejb-jar.xml files for a Stateless session bean and a CMP entity bean 1.1
|
|
Stateless Session Bean: ejb-jar.xml
|
Here is the ejb-jar.xml for a single stateless session bean.
|
|
CMP EntityBean: ejb-jar.xml
|
Here is the ejb-jar.xml for a very simple CMP 1.1 entity bean.
See also Adding CMP Fields to an EJB Deployment Descriptor
(Apple ADC) |
|
[AppServer].xml
|
The [appserver].xml file. Most app servers also require a second metadata file that describes how the
bean will be deployed. While the names are different, the content is largely the same - and it is quite important.
For one thing , the file generally describes what resources are required by each EJB. Many beans require access to databases. This information
generally appears in the <appserver>.xml file. For instance here is a sample weblogic-ejb-jar.xml file that
deploys the PersonalizationEJB from the Java Petstore.
For EJB XML reference material see EJB-QL
World |
|
Transactions,
JTA, and JTS
|
Transaction Processing (JTA and JTS): Business transaction processing is an an ancient
art. The first (not so ancient) computerized online transaction processing systems were created by Univac and IBM
in the 1960s. So online transactions are about as old as say The Grateful Dead. The first "not-online"
transaction processing of course pre-dates history itself and whoever invented it also dead.
The purpose of an EJB server - also called an EJB container is to enable on-line business transactions for the J2EE platform architecture.
A transaction is
a distinct task (unit of work) that results in the updating of financial information for the exchange of resources
(goods or services) between business entities.
When several separate systems are required to complete a transaction. This is called Distributed
Transaction Processing (DTP). DTP requires two things 1) an common
transaction interface and 2) a coordinating process. For commercial transactions, both of these must conform to
the industry standards which are the OMG OTS standard implemented by the OMG in CORBA. A system that does so is
called a distributed transaction monitor an object oriented one is called an Object
Transaction Monitor (OTM). For an overview of OTMs see: An OTM primer by Max Dolgicer, ADT Mag, August 1998. and Distributed Transaction Processing (PPT)
An EJB server is thus a special case of an OTM. It provides both a standard interface and process that conform
to these standards, and it uses the EJB architecture.
The XA Interface.
The general interface for DTM and OTM is the OMG X/OPEN Distributed
Transaction Processing XA Specification. The XA Specification defines
a distributed interface that enables remote resources to communicate their state through a series of transaction
steps. An EJB server uses JTA and JTS to communicate with other XA enabled servers. JTA is the J2EE API for this.
And JTS is an implementation of that API. There is a white paper Understanding JTA: the Java Transaction API
(DataDirect) Jul 2002 explains JTA especially with respect to databases.
The Two Phased Commit Process.
The coordinating mechanism for distributed transactions is called "two phased commits." This mechanism
enables proper coordination to take place amoung all transaction servers.
For an overview of transaction processing see Nuts and Bolts of Transaction Processing
by Dr. A.V.B.Subrahmanyam (May 1999).
Updating multiple backend systems. The
J2EE specification allows the EJB container to coordinate transactional updates on multiple RDBMS or other back
end servers within the same transaction. This can occur in the same EJB or in multiple EJBs. |
Using Transactions with EJBs
Demarcation denotes
when a transaction starts and ends. The EJB container offers three different kinds of transaction demacation:
- Client demarcation Explicitely controlled from the EJB client
- Container demarcation Deployment specified and controlled from the EJB
container
- Bean demarcation Internally managed by the bean
Client Demarcation When
using client demarcation, the EJB client is responsible for determining when a transaction begins and ends. To
use client demarcation, the EJB client must always call the EJB with a transaction context: javax.transaction.UserTransaction
returned by EJBContext.getUserTransaction().
Container Demarcation. With
container demarcation, the EJB client may call an EJB with an external transaction context - or not. The value
of the <trans-attribute> deployment descriptor determines how transactions are handled. These values are
(for EJB 1.1):
- NotSupported "unspecified
transaction context" The clients transaction context is suspended until the bean method completes.
- Supports The Client
context is propagated to the bean. If no client context, bean method is executed under "unspecified context."
- Required Client context
is propagated to the bean. If no client context is specified, the container creates a new context for the transaction.
- RequiresNew The Client
context (if any) is suspended and a new context is always created.
- Mandatory Client context
is propagated to the bean. If no client context is specified, the container throws a TransactionRequiredException
- Never Client context
is prohibited. If a client context is passed, it causes the container to throw a RemoteException - otherwise the
container operates the transaction with "unspecified transaction context."
See the JavaCaps EJB Transaction Page by Konda Balabbigari
for more information on Demarcation.
Transaction Isolation Level.
At deployment time you also specify the transaction isolation tag. There are four transaction isolation levels.The
level determines how isolated a read during transaction is from as follows:
- 1 Read Uncommitted TRANSACTION_READ_UNCOMMITTED - Can read uncommitted
data.
- 2 Read Committed TRANSACTION_READ_COMMITTED - Can not read uncommited.
- 3 Repeatable Read TRANSACTION_REPEATABLE_READ - Reading the same data
always returns the same value.
- 4 Serializable TRANSACTION_SERIALIZABLE - only this transaction can read
and write the data it uses.
See J2EE Transaction Frameworks: Distributed Transaction Primer by Dibyendu Baksi. OnJava, May 2001. Isolation levels are discussed on page 2.
Raisie the isolation level to provide more assurance that simulatenous
updates to the same backend data will not occur. But be careful.
Caution: Isolation level and drivers.
Remember that transactions are based on XA but not all drivers are XA compatible. You may encounter a JDBC driver
that have a "general" version that enables DDL operations in a "non-XA mode" and a different
version that is "XA enabled" for online processing only. Be sure you are using an XA enabled driver.
For instance, see this item and this item and read Using WebLogic jDriver for Oracle/XA in Distributed Transactions (BEA).
For more information on EJB Transactions and transaction programming see:
. A developer's
guide to EJB transaction management Kevin Boone (The K Zone)
. EJB
Transaction Management (jGuru)
|
|
Issues:
Classloading and inheritence
|
Deployment brings up a number of issues around class loading. Especially if
you are using inheritence such issues need to be addressed so that your EJBs do not fail. See WebLogic Server Application Classloading
(BEA) and Inheritance
Classpath implications Jun 2002 (Pramati Forum) |
|
Deploying to the App Server
|
The EJB vendor supplies a deployment tool - or specifies a directory into
which you place EJB jars. Some vendors, including WebLogic and jBoss, enable "hot deployment:" loading
or reloading EJBs after the container is already running.
Each EJB server vendor will have configuration files that control the EJB server. These files describe resources
the EJB container will use, independent of what EJBs are loaded into the container. |
|
EJB Clients (and servlets)
|
EJB Clients, providel access to an EJB Server. In the on-line Web environment,
EJB clients are typically an HTTP Servlet or JSP - but they don't have to be. *** See Developer Highway 101 *** Java Skyline, May 2002,
for a tutorial on servlets and EJBs using JDeveloper, Tomcat, BEA WebLogic and Oracle9i Application Server. Gopalan
Suresh Raj's Web Cornucopia provides two demonstrations of EJB Clients: the first Developing EJB Clients, presents
a very short example program. The second involves building a Servlet EJB Client.
Connecting a servlet or other EJB client to an EJB generally requires the following:
1. In the servlet create a Hashtable (to set up a Context environment).
2. Load the Hashtable with:
The provider URL - address and port of the EJB container
The Initial Context Factory defined for the EJB container you are using.
3. Create a JNDI Context using the Hashtable.
4. Do a lookup using the name you placed in the ejb-jar.xml
5. For entity beans, do a findByPrimaryKey on the bean.
Here is a simple annotated servlet example for jBoss calling an EJB called Account. Click here for EJB Vendor Conventions for connections
to BEA WebLogic, IBM WebSphere and other J2EE Application servers.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.ejb.*;
// Import for your EJB package:
import com.yourlib.account.ejb.*;
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest
req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out;
res.setContentType("text/html");
out = res.getWriter();
String acctnum="";
try {
acctnum = req.getParameter("AccountNumber");
Hashtable env = new Hashtable();
// Connection to J2EE EJB Server
// Click here for BEA, IBM, IONA, Oracle and others
out.println("Preparing environment to connect to jBoss");
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
env.put(Context.PROVIDER_URL,
"localhost:1099");
out.println("Creating JNDI Context");
Context jndiContext = new InitialContext(env);
out.println("Doing a JNDI Lookup on Home Interface");
// The name you put here must match the name
// in ejb-jar.xml in the deployment jar.
Object ref = jndiContext.lookup("Account");
out.println("Upcasting to Home Interface");
AccountHome accountHome
= (AccountHome) PortableRemoteObject.narrow(ref,
Account.class);
out.println("Now, looking up account to see if it's there.");
Account acct = accountHome.findByPrimaryKey(acctnum);
out.println("We have an Account for: "+acctnum);
String getdata=acct.sendData("Hi");
} catch (Exception e) {
out.println("Account not found: "+acctnum);
out.println("Encountered error "+e+" while looking up account");
}
}
}
Argument passing when calling an EJB:
As a rule of thumb, if you need the EJB to perform operations on an object, use a syntax like:
MyObject sendit = new MyObject();
sendit.setMyParam("data to send");
MyObject ret = acct.getMyObject(send);
String receivedata = ret.getMyParam();
When the EJB and its client are in different JVMs argument passing operate
differently. The above syntax will work in any case. For why, see BitterEJB, Chapter 6 Bitter Session States
Dec 2002, if it's still there when you read this, or this newsgroup copy (comp.lang.java.programmer,
Jan 2003).
|
|
Vendor examples
|
EJB Examples: Most EJB
servers provide examples that you can compile and run hen you download the server. Most EJB servers provide examples
that you can compile and run when you download the server. Below are on-line examples and useful instructions for
building EJB clients: |
Vendor books Wrox Press has a
series of J2EE Handbooks on J2EE deployment and administration for JBoss, IBM, and BEA. |
| |
Apple WebObjects |
Introduction
to Enterprise JavaBeans (ADC Apple)
Developing EJB Applications (PDF) (ADC Apple)
Developing an Entity Bean From a Data Model
(ADC Apple) |
| |
BEA WebLogic |
EJB Technology
Tracks (Dev2Dev BEA)
WLS 7.0 Sample: Using EJB QL in CMP
(Dev2Dev BEA)
WLS 7.0
Programming . Deployment . Admin (eDocs BEA)
Using
Weblogic Enterprise JavaBeans
Designing
a WebLogic EJB application
Building
Enterprise JavaBean examples
The
Great J2EE RoadTrip (Java Skyline)
LearnWebLogic.com |
| |
IBM WebSphere |
WebSphere Developer
Domain (IBM)
WebSphere
Studio Plug-in Central (IBM)
WebSphere
Tutorial (IBM)
WebSphereCentral (req. registration)
Enterprise
JavaBeans in 3 Easy Steps - Screen Cam VAJava |
| |
Borland Enterprise Server |
BES Petstore
Tutorial (Borland)
EJB
Develpment using JBuilder 6.0 and BES (PDF) Todd Spurling, Hartwig
Gunzer, (Borland)
Enterprise JavaBeans
Simplifying Development of Distributed Multi-tier Applications |
| |
Iona |
Iona Development Center | App
Server Zone (Iona)
Iona Product Documentation (Iona)
Iona Whitepaper Requests (Iona)
Iona
Knowledge Base: Iona Products | EJB (Iona) |
| |
JBoss |
JBOSS
3.0 Step-by-Step (pdf) Scott Pumer
Beginning EJB
programming using jBoss Kevin Boone (The K Zone)
CMP with JBoss Kevin Boone (The K Zone)
'J2EE On
Mac OS X' View J2EE (pdf) JBOSS, Eclipse,
and MySQL Bert Torfs
Writing
Stateless Session Bean and Deploying on JBoss (RoseIndia)
CMP
2.0 With JBoss 3.0 Beta Tutorial Tim Chartrand
Coding the test client (and following lessons)
JBoss 2.0 Manual:
JBoss Clients |
| |
Macromedia JRun |
Tutorial
and Article Index (Macromedia JRun Support Center) |
| |
Oracle 9iAS |
Sample
code . eSeminars . EJB Primer (OTN)
Oracle9i
AS: Design Considerations when using (CMP) Sastry Malladi Oracle,
Jan 2003
The
Great J2EE RoadTrip (Java Skyline) |
| |
Orion Server |
Orion Documentation Index |
| |
Pramati |
EJB 1.1: Multi-table support with complex Entity Beans (PDF)
(Pramati) |
| |
SunONE |
SunONE Web Technologies . Sun
ONE Studio (Sun)
Sun ONE
Studio Developer Resources (Sun)
iPlanet
Sun J2EE Guide Samples (Sun)
Enterprise
JavaBeans Tutorial Part 2:Entity Beans Robert Crowe (Sun) |
|
Performance, Practices, and
Patterns
|
This section discusses performance, best practices - especially with regards
to performance and design patterns with a substantial focus on performance. Persistence frameworks and design patterns
help deal with performance issues that need to be addressed. This section discusses
- The purpose of EntityBeans and when to use them
- Transactions vs. Content
- How persistence design patterns affect performance
- For fun and prophets - some ideas on performance |
|
"To EJB, or not to EJB"
|
There are four major question:
1) Do I need Enterprise JavaBeans at all?
2) If yes, do I need transactions?
3) If I need transactions, do I need EntityBeans?
4) If I need EntityBeans, should I actually use pessimistic locking with them?
These questions all affect performance. The best performance comes by answering "No" sooner rather than
later.
Rule of thumb: Transactions vs. content applications. As a rule of thumb, you only need EJBs at all if you if you are actually processing
transactions (or otherwise controlling and monitoring the update of back-end systems). For content presentation
purposes, you probably don't want to use EJBs. |
|
Load Balancing, Scalability, and Clustering
|
Scalability is the extent
to which a system operates under increased load without degradation. Load
balancing is the ability to distribute load across multiple service
units to improve scalability. J2EE is designed to provide load balancing across multiple containers in multiple
tiers.
Clustering means
having multiple containers work together as a unit to provide load balancing and, scalability, as well as reliability
and failover. See Clustering,
Failover and Load Balancing concepts in EAServer Prashanth Ponnachath
(Sybase) Feb 2003. |
|
Availability and failover
|
Aside from load distribution the main reason for clustering is to improve
availability. Availability
means the percentage of up time
when a system is available for use and adequate to handle a given load. Clustering is a necessity where the availability
of a single unit is not adequate. A common strategy to achieve adequate availability is to provide one extra service
unit. - as explained in WebSphere Application Server 4.x Production Hardening (pdf) Tom Alcott, Keys Botzum, (IBM) May 2002.
Failover Failover is the ability in case+
of failure of one service unit to bring in a different service unit and to continue, re-establish, or roll back
partially completed operations without interruption in service. Transaction oriented applications naturally
have very high requirements for failover. |
|
J2EE Clustering
and Coherence
|
Clustering and Failover in EJB and J2EE
J2EE Clustering and failover are usually discussed with regard to the EJB container. Failover and Recovery in WebSphere 4.0 (pdf)
Alcott, Cheng, Cocasse, Draeger, Modjeski and Wang (IBM).
Advantages of front-end clustering
It may not be helpful to try to derive load balancing and scalability only from clustering EJB containers for
deriving load balancing and scalability. This can provide performance advantages. However, you can also achieve
balanced scalability without using EJB containers. Clustering can be used with JSP/Servlet container. In fact,
for Web applications (that may or may not use EJBs) you still may need to address balancing issues for JSP/Servlet
processing. Failover can also apply to Java Message Services. See Does OC4J support JMS clustering/failover?
(Oracle9iAS JMS FAQ).
Transaction failover in the J2EE cluster In J2EE clustering, robust transaction-oriented failover is achieved through transaction
demarcation and can be enhanced by using the inter-tier propagation of transaction state. However, failover can
also be achieved using the older RDBMS replication approaches as explained in Cameron Purdy's brief response Clustering EJB's Across a Wide-Area-Network
(weblogic.developer.interest.clustering) Dec 2001.
Coherence To make
clustering work service units must be coordinated. A system that coordinates memory resident state is called coherence. Where any server has
stateful memory, a clustering solution must provide some form of coherence as mentioned above so stateful information
is cycled into other servers.
For Web application that use HttpSessions and many do, simply adding clustered EJB containers may not help very
much if at all just to achieve better load balancing.
Clustering and Failover in EJB and J2EE Failover can be implemented using J2EE clustering by using its multi-tiered propagation
of transaction state. J2EE Clustering and failover are usually discussed with regard to the EJB container. Failover
and Recovery in WebSphere 4.0 (pdf) Alcott, Cheng, Cocasse, Draeger,
Modjeski and Wang (IBM). However, failover can also be achieved using the older RDBMS replication approaches as
explained in Cameron Purdy's brief response Clustering EJB's Across a Wide-Area-Network
(weblogic.developer.interest.clustering) Dec 2001. It can also apply to Java Message Services. See Does
OC4J support JMS clustering/failover? (Oracle9iAS JMS FAQ).
Web and front-end clustering
For front-end-heavy applications it is probably not helpful to to think only of clustering EJB containers for
deriving load balancing and scalability. Clustering of front-end containers can improve performance too. And you
can also achieve load balancing and scalability in the JSP/Servlet layer without using EJB containers at all.
In addition, for Web application that use HttpSessions and many do, simply adding clustered EJB containers may
not help very much if all you want is to just achieve better load balancing.
Coherence Clustering
solutions require coordinating the work of service unit. Coordinating memory resident state among servers is called
coherence. To provide
clustering of servers that use stateful memory, a clustering solution must provide coherence so that the stateful
information can be cycled into other servers.
Some vendors implement coherent caching in the JSP/Servlet layer for HttpSessions. Or you can purchase a coherent
cache solution from Gemstone or Tangosol.
Clustering of EJB applications that use stateful session beans or entity beans also can benefit from coherent solutions.
Some J2EE vendors and the J2EE coherence add-on vendors (just mentioned) provide coherence mechanisms for EJB.
Writing Clustered EJB Applications
There are some guidelines and limitations to follow to make an application work in a clustered environment. See
for instance Design
for Clustering by jeet1111 on Pramati Forum. EJB 2 Clustering with Application Servers
by Tyler Jewell of BEA (OnJava) Dec 2000, EJB Clustering mit JBoss Sabine
Winkler (OIO), Jan 2003. See Understanding Object Clustering (BEA). Also
CallRouter exception in WLS 6 (weblogic.developer.interest.clustering). |
|
Transaction Strategies: Entity Beans and Locking Mechanisms
|
SessionBean-based transactions. Most
transaction work can be written effectively using SessionBeans. If you have only one back-end XA server (e.g. an
RDBMS) you can get by with Session beans alone.
When to use EntityBeans
An EntityBeans represents a persistent entity - often a database entity in memory. There are all kinds of bad advise
all over the Web on when to use EntityBeans. Their only real purpose is if your EJB server is monitoring a transaction
where there are two other XA compatible servers involved.
For instance, you may need to work with two databases or one endpoints may be a database and another is some other
enterprise system and both must be updated concurrently -- in a single transaction. This view is presented by Vince
Huston who writes "The purpose of Entity Beans is to manage
concurrent access to shared persistent data" see Incremental
J2EE by Vince Huston.
A better question is "When not to use EntityBeans" and the answer is "most of the time." My
sense is that you do not need and should not use EntityBeans at all about 80% of the time.
Optimistic vs. Pessimestic locking
About 98% you don't need pessimistic locking. See PuneJava Future Trends in EJB See also Oracle9i
Application Server Design Considerations when using Entity Beans with Container Managed Persistence (CMP) Sastry Malladi Oracle, Jan 2003 and Optimistic Locking pattern for EJBs
Yasmin Akbar-Husain and Eoin Lane (JavaWorld) July 2001. |
|
Database accesses and granularity
|
One major improvement you can make is to reduce the number and frequency of
database accesses. 'Granularity
refers to how many data items are represented by one bean. This is generally the same as the number of items you
read from a database to provide all the information the bean needs.
A so called 'simple' EntityBean that represents one row in a database table is often considered too fine-grained
and may not perform very well. Craig Larman has a pattern that relates granularity called the The Aggregate Entity Bean Pattern. |
|
CMP vs. BMP
|
If you require EntityBeans, it is now recommended that you use CMP as provided
by EJB 2.0 (J2EE 1.3) and beyond - and let the container manage persistence rather than using BMP. BMP Entity beans
suffer from the "N +1" problem where a Find method results in two reads. This and other useful information is described
by Rickard Oberg see Review of "The Petstore Revisited." |
|
Persistence Stratiegies and Tools
|
Rather than use entity beans just to represent a domain model (even though
this looks convenient) it is better to model persistent objects in the domain using a persistence tool. The tool
can help you to resolve the EJB vs. no EJB question and the EntityBean vs. no EntityBean questions.
Persistence patterns, frameworks and open source. If you only trust code you can see, you can use an open source tool or implement
a persistence layer design pattern on your own. A persistence tool or a persistence pattern can enables you to
create a model and delay the choice of implementation details.
EJB specific persistence tools.
While some tools minimize your use of EJBs, others help on a detailed level when you actually use EJBs by implementing
locking strategies. Check the Database page for persistence products that either provide design decisions or provide EJB
specific behaviors.
Multiple XA connection JDBC drivers
Another alternative for dealing with multiple database systems, is a multiple XA JDBC driver such as like isocra or DataDirect. |
|
Performance and monitoring
|
Articles: Monitoring Performance with WebSphere
Ruth Willenborg (ePro) Jan 2003. Oracle9i JDeveloper Profiling Java Code (Oracle)
Aug 2002. Review
of WebSphere Studio Profiling on JavaPerformanceTuning.com. Strategies
and Resources for Java Testing Jay Mellman (Mercury Interactive)
Tool
Report: J-Sprint (JavaPerformanceTuning)
Tools: OptimizeIt
(Borland) PerformaSure, JProbe (Sitraka) Topaz (Mercury Interactive) IntroScope (Wily) J-Sprint (JSprint) BeanTest (Empirix) |
|
Pattern Resources
|
There are four books that discuss design patterns with J2EE in general:
. Core J2EE Patterns by Deepak
Alur, John Crupi, Dan Malks (Sun) 2002.
. J2EE Design Patterns Applied
Matjaz Juric, Nadia Nashi, Craig Berry, Meeraj Kunnumpurath, John Carnell, Sasha Romanosky (WROX) 2002 - Includes
a persistence framework.
. Enterprise JavaBeans Design Patterns
Floyd Marinescu, (John Wiley and Sons) 2002.
. Applied Java Patterns Stephen
A. Stelting, Olav Maassen (Sun) 2002.
. Java Enterprise Design Patterns: Patterns in Java Volume 3, by Mark Grand (John Wiley and Sons) 2001. - Discusses patterns for transactions and 2-phased
commits. |
|
Performance Resources:
(For Fun - and Prophets)
|
For Fun and Prophets dept. (Various resources and musings on existence
and EJB performance).
***.
EJB
design performance tips by prophet Jack Shirazi on JavaPerformanceTuning.com.
The name of the Web site says it all - will take you a long
time to read this site and worth every minute of it too.
. Java theory and practice by prophet
Brian Goetz, master of the famous DCL provides insight into the mysteries of JTS.
Especially see: Understanding JTS, Part 3 -- Balancing safety and performance
(IBM) May 2002.
. 101 Damnations. This ain't no party! This ain't no Disney! This ain't no foolin' around... Discusses the authors view of problems with EJBs (Software Reality)
. Bitter
EJB Review project, The Bitter Prophets (TheServerSide) Soon to
be a major book.. describes problems and solutions too.
. Is EJB always necessary? by Patrick Lightbody
and Rebolutionary Weblogist Mike Cannon-Brookes, May 2002 and the community response in The
Necessity of EJB by Mike Cannon-Brookes Sep 2002.
Extra credit: Thomas
Davis provides some valuable hints to managing network traffic in Direct network traffic of EJBs,
JavaWorld, November 1999. And Jeff Gallimore provides some performance guidelines in Tips on Implement Enterprise JavaBeans,
Java-Pro Mar 2000 (article also appeared Jul 99 Enterprise Development as Implement Enterprise JavaBeans has
been slightly reworked). 12 Tips for Better EJB Performance Krishna Kothapalli and Raghava
Kothapalli. EJB
Performance (PDF Slides) Dennis Sosnoski (SeaJUG) Mar 2002 covers
EJB 1.1 and early EJB 2.0. |
| |
|
|
EJBs with IDE Tools
|
A number of J2EE-enabled IDEs provide the ability to generate, deploy and
test run EJBs on various application servers as listed on the Architecture page. Other tools such as BEA WorkShop and CapeClear Studio can take existing EJBs
and set up Web services from them. |
|
Automatic builds, tests
|
Using IDEs, plug-ins, or tools like you can automate builds and testing procedures.
The IDEs themselves sometimes interface with Ant to automate build processes. If the IDE you are using doesn't
do this, you can use Ant on your own.
Ant is quite useful for this purpose. For instance see Using Ant and WebLogic EJBs Jesse
E. Tilly OnJava, Jun 2001. Ant runs cross-platform (on different operating systems and app server) and it's use
is not limited to building, deploying, and testing EJBs - or to WebLogic. |
|
Special Topics
|
Use JNDI to retrieve the EJBContext for EJB 1.1 see: Create forward-compatible beans in EJB, Part 1,
Page 2, Listing 3B by Richard Monson-Haefel JavaWorld, Dec 1999. |
|
Book References:
|
Enterprise JavaBeans |