HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

This article, which discusses some of the implications of EJB development, includes a tutorial that allows hands-on sampling of some EJB development tools by installing the IBM VisualAge for Java CD found in next month's issue of JDJ.

Enterprise JavaBeans (aka EJBs) are fast becoming a mainstay in Web-based business applications. They're not trivial to develop, though at least not if you're developing them by hand and ignoring the EJB tools already available to automate (and thus simplify) your development tasks.

If you earn your living as a professional Java programmer, you know that enterprise beans are nonvisual, server-side software components that conform to Sun Microsystems' EJB specification. Enterprise beans allow you to develop platform-neutral, distributed applications that run on virtually any EJB-compliant server.

EJB technology simplifies server-side application development by delegating many of the common system-level programming tasks transactional semantics, data persistence, security and workload management to the EJB server providers. This allows you to focus primarily on the application business logic when developing enterprise beans.

Enterprise beans and their many benefits have been well documented in past issues of Java Developer's Journal. A complete description of EJB technology and its advantages is found in Sun Microsystems' EJB 1.0 and 1.1 specifications at http://java.sun.com/products/ejb/docs10.html and http://java.sun.com/products/ejb/docs.html.

While they play an increasingly important role in the development of enterprise Web applications, developing EJBs presents some significant challenges. After we examine some of the challenges, we'll look at a solution that can help simplify development. This solution is found in the WebSphere application development tools that are part of IBM's VisualAge for Java product, which we'll test-drive with a short, hands-on tutorial.

The Challenges
Despite the many advantages of enterprise beans, they are technologically complex and developing them is generally not a simple task. To create an enterprise bean, you must follow a set of interfaces defined by the EJB specification. For example, in addition to defining an enterprise bean class, you must define both home and remote interfaces for each enterprise bean. The latter defines the client's view of the enterprise bean's business methods; the former defines the client's view of the bean's object life-cycle. This involves such events as the creation and removal of the enterprise bean.

You also need to ensure that the methods defined in the enterprise bean's interfaces and classes are kept consistent. And if you're creating an entity bean, you must define its persistence fields and map them to a persistent datastore, such as a relational database. Once you've created the enterprise bean, you need to target it to a specific bean container by generating the implementation classes for the home and remote interfaces. Then you need to test the home and remote methods. Finally, once testing is complete, you need to package the bean for installation on a production server.

This isn't an exhaustive look at the challenges associated with developing enterprise beans, but it should give you a feel for their underlying complexity. Fortunately, there are ready-made solutions that can help you develop enterprise beans quickly and effectively.

One Solution
Although you can develop enterprise beans by hand, it's generally faster and easier to use a set of application development tools specifically designed for the task that mask much of the complexity. The IBM WebSphere tools built into VisualAge for Java enable you to use VisualAge interactively with other Web development products, such as WebSphere Studio and the WebSphere Application Server. The tools include:

  • WebSphere Test Environment
  • JSP/Servlet Development Environment
  • EJB Development Environment

The WebSphere Test Environment allows you to test servlets, JSP files and enterprise beans in a runtime environment that's essentially the same as that provided in the WebSphere Application Server. This enables you to develop code for deployment to the WebSphere Application Server or to other application servers from non-IBM vendors. The JSP/Servlet Development Environment lets you run, monitor and debug servlets and JSP files that you've created in WebSphere Studio or other Web development products. And the EJB Development Environment enables you to develop enterprise beans and associated EJB components. Since enterprise beans are the focus of this article, we'll take a closer look at this environment.

The EJB Development Environment
You can use this specialized environment to develop and test enterprise beans that conform to the EJB specification. In the VisualAge for Java Workbench, the EJB page is the heart of this environment. It's where all your enterprise beans and related components reside, and it's where you accomplish all your enterprise bean development activities. In the EJB page (shown in Figure 1) you can access and run the EJB Development Environment tools, as well as write and edit any required business logic.

Figure 1
Figure 1:

The EJB Development Environment tools simplify your development tasks by generating most of the infrastructure code for your enterprise beans. Specifically, they:

  • Create EJB groups to hold your enterprise beans.
  • Create new session enterprise beans or entity (BMP or CMP) enterprise beans.
  • Inherit properties from other enterprise beans (e.g., CMP fields, methods, control descriptor attributes).
  • Import existing enterprise beans.
  • Add home and remote interfaces.
  • Build persistence into enterprise beans by adding, defining and mapping CMP fields.
  • Create and map associations between CMP entity beans.

  • Set deployment and control descriptors.
  • Generate deployed classes.
  • Create and edit access (adapter) beans.
  • Verify that enterprise bean code is consistent and conforms to the EJB specification.
  • Maintain source code and generated code using the built-in team and versioning capabilities.
  • Test and debug enterprise beans using a generated test client and a test server.
  • Export your code for deployment to production servers.
Although all elements of the EJB Development Environment play an important role, access beans and the test client warrant some special attention.

Access beans, sometimes known as adapter beans, serve as JavaBean wrappers for your enterprise beans. Generated by a wizard and typically used by client programs such as JSP files, servlets or even other enterprise beans, they allow you to hide the home and remote interfaces of an enterprise bean and adapt them to the JavaBeans programming model. This simplifies the interface between enterprise beans and servlets or JSP files by providing a JavaBeans interface that's recognized by all Java developers. Access beans introduce advanced local caching of enterprise bean attributes, which reduces the number of remote calls and provides faster access to enterprise beans.

The test client is an application you can generate automatically and run to test each enterprise bean that's running in the EJB test server. It features its own user interface and allows you to test individual methods in the home and remote interfaces of an enterprise bean. It makes testing enterprise beans as easy as testing local Java programs and saves you the effort of coding your own test client.

More detailed information about the EJB Development Environment and other WebSphere tools is found in "WebSphere Support in VisualAge for Java 3.0" at www.software.ibm.com/vadd.

The Tutorial
In this tutorial you'll create and test an enterprise bean using some of the core tools in the EJB Development Environment. For our purposes assume that a small, unnamed bank has asked you to develop a simple banking application where, for "tax purposes," information about customer bank accounts is limited to a bank account number and the balance in the account.

You decide to create an enterprise bean that enables customers to create their own bank accounts and specify the account numbers, query their bank balances, and make deposits and withdrawals. (Customers should also be able to delete their accounts in case they suddenly need to take an extended trip out of the country!)

Since data in a bank account needs to persist after a customer banking session ends, you need to create an entity enterprise bean. You don't want to spend a lot of time writing the logic required to store the data, so you decide to use a container-managed persistence (CMP) entity bean, which delegates the data storage tasks to its container.

Since you're a Java whiz and familiar with EJB technology, you know that creating, finding and deleting accounts are handled by the home interface of the enterprise bean, which extends the javax.ejb.EJBHome interface defined by the EJB specification. You also know that depositing, withdrawing and obtaining a balance are handled by the remote interface of the enterprise bean, which extends the javax.ejb.EJBObject interface. (This interface contains the business methods that a client application can call on an enterprise bean. The client application has access only to the methods that a developer chooses to expose through the remote interface. It doesn't have direct access to the enterprise bean.)

Now you know the "history" behind the tutorial, you're ready to begin your short odyssey into enterprise bean development.

Step 1: Prepare for the tutorial.
To allow you a hands-on experience of the tutorial, next month's issue of JDJ includes the following two CDs:

  • IBM VisualAge for Java, Entry Enterprise Edition for Windows
  • IBM DB2 Universal Database Personal Edition for Windows
To continue with the tutorial, you need to install these products, create the sample database and perform some basic setup tasks. Installation and setup instructions for the tutorial can be found at www.ibm.com/software/vadd/homedata/va-db2.

Step 2: Create the project and package.
Now that you've finished preparing for the tutorial, you can create the project and Java package. (A project is a receptacle used to hold a collection of related Java packages, much like a directory in the file system.)

  1. Open the VisualAge for Java Workbench, click the Projects tab, then click the Add New or Existing Package to Workspace icon.
  2. In the Add Package SmartGuide Project field, type SimpleEJB.
  3. In the Create a new package named field, type netbank.
  4. Click Finish. The new project and package are added to the Workbench.

Step 3: Create an EJB group.
In this step you create an EJB group, which is simply a receptacle to hold and organize related enterprise beans.

  1. Click the EJB tab to open the EJB page of the EJB Development Environment.
  2. Click the Add EJB Group icon to open the Add EJB Group SmartGuide.
  3. In the Project field, type SimpleEJB, and in the Create a new EJB group named field, type BANK.
  4. Click Finish to generate the code into the associated project.

Step 4: Create the enterprise bean.
Now that the EJB group is created, you can create the enterprise bean. Since you need to store persistent data for the account balance and you don't want to write your own logic to store the data, you'll create a CMP entity bean.

  1. Click the Add EJB Bean icon to open the Create Enterprise Bean SmartGuide.
  2. In the Bean name field, type Account. (AccountBean appears as the default entry in the Class field.)
  3. In the Bean type field, select Entity bean with container-managed persistence (CMP) fields.
  4. Click Next. The Define Bean Class Attributes and Interfaces page appears. (Note that, by default, AccountHome is displayed in the Home interface field, Account is displayed in the Remote interface field and AccountKey is displayed in the Key class field.)
  5. Ensure that the Create helper finder interface to support finder methods checkbox has been selected.
  6. Click Add beside the Add CMP fields to the bean list box to open the Create CMP Field SmartGuide. You'll use this SmartGuide to set up the fields to store the bank account number and the balance in the account.
  7. In the Field Name field, type primaryKey, then, in the Field Type field, select java.lang.String. This field will be used to find or create new instances of AccountBean.
  8. Select the Key Field checkbox, then click Finish to add the CMP field and close the SmartGuide.
  9. Open the Create CMP Field SmartGuide again so you can add another CMP field ;to store the balance in the bank account. In the Field Name field, type balance. Beside the Field Type field, click Browse to open the Field Type dialog box, then, in the Pattern field, type BigDecimal and click OK to close the dialog box.
  10. In the Initial Value field, type new java.math.BigDecimal(0). Ensure that the Access with getter and setter methods checkbox is checked and that the public radio buttons are selected for the getter and setter methods. (In Java, field values are retrieved by a getter method and set with a setter method. The SmartGuide generates the code to both get and set the balance in the account.)
  11. In the Create CMP Field SmartGuide, click Finish to add the CMP field. The Define Bean Class Attributes and Interfaces page should now look like Figure 2.
  12. Click Finish to generate the enterprise bean.

Figure 2
Figure 2:

The code in Listing 1 appears in the Source pane.

Step 5: Add the required methods.
Now you need to add some new methods so you can deposit and withdraw from the account.

  1. In the Types pane of the EJB page, select AccountBean.
  2. Click the Create Method or Constructor icon to open the Create Method SmartGuide.
  3. Ensure that Create a new method is selected, then click Next to open the Attributes SmartGuide.
  4. In the Method Name field, type deposit, then, beside the Return Type field, click Browse to open the Field Type dialog box.
  5. In the Pattern field, type BigDecimal and click OK to close the dialog box.
  6. Now you're ready to add and define a parameter for the amount of money to be deposited in the account. Click Add to open the Parameters dialog, then, in the Name field, type amount.
  7. Select the Reference Types radio button, then, in the field below, type BigDecimal to specify BigDecimal as the return type.
  8. Click Add, then click Close to close the Parameters dialog.
  9. Select Finish to generate the code. The method will take the BigDecimal value amount as a parameter, then return an updated BigDecimal value balance.

The following code appears in the Source pane:

public java.math.BigDecimal
deposit(java.math.BigDecimal amount)
return null;

Step 6: Implement the deposit and withdraw methods.
Next, you implement the deposit and withdraw methods to perform the business logic. The deposit method will retrieve the current balance using the getBalance method, add the input amount to the balance, then use the setBalance method to store the new balance.

  1. In the Source pane replace the existing code with the following code:

    public java.math.BigDecimal
    deposit(java.math.BigDecimal amount)
    return balance;

  2. In the Source pane right-click and select Save.
  3. In the Source pane add the withdraw method to the program by changing the word deposit to withdraw, then changing the word add to subtract.
  4. In the Source pane right-click and select Save to create the withdraw method.

Step 7: Promote the methods to the remote interface.
Now that you've finished your Java coding, you need to promote the getBalance, deposit and withdraw methods to the remote interface so you can manage your account. (Note that you don't promote the setBalance method to the remote interface. This would enable customers to set their own bank balance for any amount they like!)

  1. In the Members pane right-click the getBalance method and select Add to > EJB Remote Interface. An icon appears beside the method to indicate that it's now part of the remote interface.
  2. Using the same procedure, add both the withdraw(BigDecimal) and deposit(BigDecimal) methods to the remote interface.

Step 8: Generate the schema, map and database table.
Since your EJB group now contains an enterprise bean, you can use the top-down approach to generate a schema and map from the EJB group. In this approach the enterprise bean design determines the database design. The generated schema contains one table for each CMP entity bean in the EJB group. In the table each column corresponds to a CMP field and the generated mapping maps the field to the column.

  1. Open a Windows NT command window and issue a db2start command to ensure DB2 is running.
  2. In the Enterprise Beans pane right-click the BANK group and select Add > Schema and Map from EJB Group. This creates the default schema.
  3. Click the Open Database Schemas Browser icon to open the Schema Browser. In the Schemas pane select BANK, then, in the Tables pane, select Account. This displays the columns in the table.
  4. To export the schema, from the Schemas menu select Import/Export Schema > Export Entire Schema to Database. The Database Connection Info dialog box opens.
  5. In the Connection Type field, select COM.ibm.db2.jdbc.app.DB2Driver.
  6. In the Data source field, type jdbc:db2:sample, then click OK. The Console window opens to confirm that an Account table was created with a primaryKey column for the account number and a balance column for the balance in the account.
  7. Close the Schema Browser.

Step 9: Generate the deployed code and the test client.
Now you need to generate the deployed code, which consists of the home interface code and the communications code (stubs and ties) that serves as the middleware used to connect the client to the server. You also need to generate the test client to test the enterprise bean.

  1. In the Enterprise Beans pane right-click BANK, then select Generate > Deployed Code and wait for the code to be generated.
  2. In the Enterprise Beans pane right-click BANK again and select Generate > Test Client. This automatically generates the test client code and a default user interface so you can test the enterprise bean without coding a full-blown user interface.
Step 10: Publish the enterprise bean to the EJB test server.
Now that you've generated a test client, you need to publish the enterprise bean to the EJB Server Configuration browser, set some properties, then start the required servers.
  1. In the Enterprise Beans pane right-click BANK and select Add To > Server Configuration. The EJB Server Configuration browser appears.
  2. In the Servers pane right-click Persistent Name Server and select Start Server.
  3. In the Console window ensure that the Persistent Name Server process is selected in the All Programs pane and wait until the message "Server open for business" appears in the Output pane. (If the Persistent Name Server fails to start and you're using a disconnected laptop computer, install the loopback adapter from your Windows NT CD, configure it, then try starting the Persistent Name Server again.)
  4. In the Servers pane of the EJB Server Configuration browser, right-click EJB Server (server1) and select Properties to open the Properties dialog box.
  5. In the Data Source field change the existing value from jdbc:db2:sampleDB to jdbc:db2:sample.
  6. In the Connection Type field, ensure that COM.ibm.db2.jdbc.app.DB2Driver is selected, then click OK to close the dialog box.
  7. Right-click EJB Server (server1) and select Start Server. In the Console window select the EJB Server process. Wait until the message "Server open for business" appears.

Step 11: Run the test client.

  1. In the EJB Server Configuration browser expand the BANK group and select the Account enterprise bean, then click the Run Test Client icon. The Connect page of the test client appears.
  2. On the Connect page click the Connect button. The Home interface page
  3. Ensure that create(String) is selected, then, in the Parameters field, type Acct355 and click Send. This creates an instance of a bank account with Acct355 as the primary key. The Remote interface page appears.
  4. Ensure that the deposit(BigDecimal) method is selected, then click New to open the Constructors dialog.
  5. Select the constructor new BigDecimal(String), then, in the Parameters field, overtype the null value with the value 4500.00.
  6. Press Send, then press Done to close the Constructors dialog.
  7. In the Remote interface page press Send. In the Result display field a message confirms that the amount of 4500.00 has been deposited into the account, as shown in Figure 3.

Figure 3
Figure 3:

Congratulations! You've just created and tested a fully functional enterprise bean that you can use in the simple banking application requested by that small, unnamed bank!

Author Bios
Lucy S. Barnhill is a development manager at the IBM Research Triangle Park facility in Raleigh, North Carolina. She manages the Development and Information Development teams working on VisualAge persistence tools.
[email protected]

Angus McIntyre is the marketing manager for VisualAge for Java. He has 16 years of experience at the IBM Toronto Lab.
[email protected]

Rob Stevenson, an information developer at the IBM Toronto Lab, writes online help and publications for the VisualAge for Java product.
[email protected]


Listing 1 

import java.rmi.RemoteException; 
import java.security.Identity; 
import java.util.Properties; 
import javax.ejb.*; 
 * This is an Entity Bean class with CMP fields 
public class AccountBean implements EntityBean { 
 public java.math.BigDecimal balance = new java.math.BigDecimal(0); 
 private javax.ejb.EntityContext entityContext = null; 
 public java.lang.String primaryKey; 
 final static long serialVersionUID = 3206093459760846163L; 


All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.