Accelerate EJB 2.0 development with EJBGen

Simplify development and maintenance in your EJB CMP 2.0 model

Developers who have worked with Enterprise JavaBeans (EJB) technology since its inception have experienced the hassle of the EJB development lifecycle. When I started to work with EJB 1.1 containers, I had to maintain classes and interfaces, usually using the Business Interface pattern to spot errors at compile time. I even had to manually create, edit, and maintain the XML deployment descriptors. In addition to being bug-prone, those steps usually delayed my development process.

Since then, the implementation of various projects has eased the EJB development process by automatically generating the deployment descriptors and remote, home, and local interfaces -- based on information provided by the bean class (that which implements javax.ejb.SessionBean or javax.ejb.EntityBean).

In this article, I will present EJB expert Cedric Beust's EJBGen tool. EJBGen limits your code editing to just one file, the bean class, which you annotate with javadoc tags. EJBGen, which is basically a doclet, parses your entity bean source file and generates the remote, home, and local interfaces for you.

EJBGen, doclet, and javadoc explained

As a Java developer, you certainly know javadoc, the JDK tool that lets you generate some HTML documentation based on comments you embed in your source code.

Javadoc uses the Doclet API to specify the content and format of its output. Sun Microsystems provides a default doclet that outputs HTML documentation. That doclet is composed of the classes in the com.sun.tools.doclets, com.sun.tools.doclets.standard, and com.sun.tools.doclets.standard.tags packages. The default doclet is used unless you select the javadoc's -doclet option. However, you can write your own doclet for enhanced functionality.

EJBGen is a doclet that outputs Java source code (local, remote, home interfaces) and XML deployment descriptors (ejb-jar.xml). In addition, EJBGen can generate proprietary deployment descriptors, weblogic-cmp-rdbms-jar.xml and weblogic-ejb-jar.xml, for BEA WebLogic 6.1.

EJBGen is easy to use because:

  • You can quickly implement a large schema and entity bean relationships in just a few days
  • You maintain just one class, the bean class
  • You no longer manually maintain XML deployment descriptors

To show how to use EJBGen, I implemented an example from the EJB 2.0 specification, section 10.3.12: "An Order Entity Bean that Has Relationships with Line Items and Customers."

If you're new to EJB, I strongly suggest you read Chapter 10 of the EJB 2.0 specification: "Entity Bean Component Contract for Container-Managed Persistence."

Entity bean CMP 2.0

I don't intend to give you an in-depth presentation on entity beans; that would exceed the scope of this article. However, I would like to outline some of the many features and advantages that container-managed persistence (CMP) 2.0 can bring to your projects:

  • An entity bean CMP class is small and maintainable
  • The container generates the SQL code for persistence and finder queries, based on your portable EJBQL queries
  • With a 2.0-compliant container, you can define relationships between entity beans (one-to-one, one-to-many, and many-to-many) and let the container manage these relations
  • The container implements lazy loading techniques and other performance tricks
  • You can focus on the business code, rather than the technical infrastructure
  • You are not restricted to one vendor

Obviously, the EJB specification is not perfect. Some people were turned away by entity bean CMP in the EJB 1.1 specification, so they disregard it in EJB 2.0. However, if you're one of those people, you should reconsider your position and see how much this technology has improved.

Moreover, the move to the EJB 2.0 CMP model will protect your investment. By adopting CMP, you minimize the move to next-generation, specification-compliant containers; you also allow the container to regenerate the code behind the scenes, and EJBGen to automatically produce specification-compliant XML deployment descriptors. You therefore automatically take advantage of container improvements. Exciting updates, especially on the security side, are currently being defined for the EJB 2.1 and J2EE (Java 2 Platform, Enterprise Edition) 1.4 specifications. (See Java Specification Requests JSR 151 and JSR 153.)

Okay, I'll stop preaching; now let me prove it.

The example

EJB 2.0 provides some sample code to illustrate the relationships and local interface concepts in the EJB 2.0 CMP model. The section 10.3.12 describes this example as an:

...Order entity bean with relationships to line items and customers, which are other entity beans within the same local scope. Product is indirectly related to Order by means of the relationship between LineItem and Product.

We will simply implement this example. I've tested the source code for this article on the Win2K platform with the following tools:

  • BEA WebLogic Server 6.1
  • Microsoft MS SQL Server
  • Inprise JBuilder Personal
  • Sun Microsystems JDK 1.3.1

After a short introduction to relationships, we will create the tables in the database that represent Order, LineItem, Customer, Product, and Address. Steps 1 and 2 describe how to implement your entity beans without relationships using EJBGen. Step 3 defines those relationships. As a bonus, I will provide an EJB 2.0 business method. This business method adds a LineItem to an Order and demonstrates the use of value objects and local interfaces.

Step 1: Create the tables in your database

To understand how to create your database tables, you must first understand how the EJB 2.0 model creates relationships and the implication of those relationships on the tables. For beginners, I recommend you develop the entity beans without relationships, and then add the relationships once the beans have been unit tested. Obviously, the more you gain experience with the 2.0 model, the more easily you can develop the beans with their relationships from the start.

The following list describes the relationship types and their physical mappings:

  • One-to-one relationship: This relationship involves a physical mapping from a foreign key in one bean to the primary key in another bean. A primary key uniquely identifies a piece of data. The foreign key creates an association between the tables (a one-to-one, one-to-many, or many-to-many association), and therefore, an association between objects through container-managed relationship (CMR) fields.

  • One-to-many relationship: This relationship involves a physical mapping from a foreign key in one bean to the primary key in another bean (like the one-to-one relationship). The constraint: the foreign key is always contained in the table that occupies the relationship's many sides. An Order can have multiple LineItems. The foreign key is in the LineItem table and references the primary key in the Order table.

  • Many-to-many relationship: This relationship involves a physical mapping to a join table used in the RDBMS (relational database management system). Each row in this join table contains two foreign keys that map to the primary keys of the relationship entities.
Note
You often need to define attributes in the join table. The EJB 2.0 specification does not solve the problem of accessing, adding, and removing these attributes from the join table because there is no corresponding entity representation. To solve this, you have to abstract the join table using an entity CMP bean that has two one-to-many relationships with the two other tables.

The data physical view

The following diagram represents the Order, Customer, LineItem, Product, and Address tables, plus the relationships between them.

The proceeding tables describe for each column its key type (primary or not; auto means the database increases the integer value -- the key increments automatically when a record is inserted), its name, its data type (String, Integer, and so on), and whether or not it allows the null type. A blank cell (-) means that the key type is neither primary nor foreign. Each table has its own corresponding bean class implementation (for the Order table, there is a corresponding OrderBean entity CMP bean, for example).

Tables and relationships

An Order can have only one Customer, but a Customer can have multiple Orders. An Order can have multiple LineItems, with a minimum of one LineItem per Order. The Order table defines the columns shown in Table 1.

Table 1. Order table

Key typeColumn nameData typeAllows null
Primary, autoorderidStringNo
-statusStringNo
-creditApprovedBooleanYes
Foreign key to CustomercustomerfkStringYes

A Customer can have zero or more Orders. The Customer table defines the columns shown in Table 2.

Table 2. Customer table

Key typeColumn nameData typeAllows null
PrimaryemailStringNo
-firstnameStringNo
-lastnameStringNo

A Product can have multiple LineItems. The Product table defines the columns shown in Table 3.

Table 3. Product table

Key typeColumn nameData typeAllows null
Primary, autoproductidStringNo
PrimaryproductnameStringNo
-priceDoubleNo

A LineItem can have only one Order and one Product. The LineItem table defines the columns shown in Table 4.

Table 4. LineItem table

Key typeColumn nameData typeAllows null
Primary key, foreign key to OrderorderfkStringNo
Primary key, foreign key to ProductproductfkStringNo
Foreign key to AddressaddressfkStringNo
-quantityIntegerNo
-statusStringNo
-taxDoubleNo
-shipmentdateDateNo

The Address table defines the columns shown in Table 5.

Table 5. Address table

Key typeColumn nameData typeAllows null
Primary keyaddressidStringNo
-street1StringNo
-street2StringYes
-postcodeStringNo
-cityStringNo
-countryStringNo

You can download the DDL (data description language) script from the Resources section to create the schema in your database.

Step 2: Write the CMP entity beans without relationships

This step is important, but not mandatory. Developing the beans without the relationships is a simple pragmatic approach I usually take in the development process. Testing the basic getters and setters is easier without the relationships. This would be the first step in testing your beans, prior to testing the relationships. As you get used to the EJB 2.0 model, you can begin to merge Steps 2 and 3.

I will focus on the Order table that has a one-to-many relationship with LineItemCustomer. I will introduce a few simple EJBGen tags.

Again, remember EJBGen's main advantage here: we only work on the bean class; EJBGen generates the rest. The bean class without the relationships looks like this:

package org.jyperion.order;
import org.jyperion.framework.AbstractEntityBean;
import org.jyperion.framework.PrimaryKeyGenerator;
/**
 * OrderEntityBean
 *
 * @ejbgen:entity
 *  ejb-name            = OrderBean
 *  table-name          = OrderBean
 *  data-source-name    = jdbc/JavaWorldPool
 *  prim-key-class      = java.lang.String
 *  default-transaction = Required
 *
 * @ejbgen:jndi-name
 *   remote =  OrderBean
 *   local  =  OrderBeanLocal
 *
 * @ejbgen:finder
 *   signature             = "Collection findAllOrders()"
 *   ejb-ql                = "SELECT OBJECT(O) FROM OrderBean O"
 *   transaction-attribute = Required
 *
 * @ejbgen:finder
 *   signature             = "Collection findAllPendingOrders()"
 *   ejb-ql                = "SELECT OBJECT(O) FROM OrderBean O WHERE O.status = 'PENDING'"
 *   transaction-attribute = Required
 *
 * @author Thierry Janaudy
 * @date 12 November 2001
 * @version 1.0
 */
public abstract class OrderBean extends AbstractEntityBean {
  ///////////////////////////////////////////////////////
  // Container Managed Persistent Fields               //
  ///////////////////////////////////////////////////////
  /**
   * @ejbgen:cmp-field column = orderid
   * @ejbgen:primkey-field
   */
  public abstract String getOrderId();
  public abstract void setOrderId(String orderid);
  /**
   * @ejbgen:cmp-field column = status
   * @ejbgen:remote-method
   * @ejbgen:local-method
   */
  public abstract String getStatus();
  public abstract void setStatus(String status);
  /**
   * @ejbgen:cmp-field column = creditApproved
   * @ejbgen:remote-method
   * @ejbgen:local-method
   */
  public abstract Boolean getCreditApproved();
  public abstract void setCreditApproved(Boolean creditApproved);
  ///////////////////////////////////////////////////////
  // Container Managed Relation Fields                 //
  ///////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////
  // Create methods                                    //
  ///////////////////////////////////////////////////////
  public String ejbCreate(String status) {
    this.setOrderId(PrimaryKeyGenerator.getUUID(this));
    return null;
  }
  public void ejbPostCreate(String status) {
    this.setStatus(status);
  }
  ///////////////////////////////////////////////////////
  // Overridden methods                                 //
  ///////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////
  // Business methods                                  //
  ///////////////////////////////////////////////////////
}

This bean class is part of the org.jyperion.order package that you can find in the source code.

As you can see, the Javadoc is pretty straightforward:

1 2 Page 1
Page 1 of 2