Brewing entity Enterprise JavaBeans

Harness the power of entity beans

Enterprise JavaBeans (EJB) represents a fundamental change in the world of enterprise software. The EJB specification provides the software development community with the component model, maintains interoperability between EJB and non-EJB applications (including non-Java-based applications like CORBA), and features straightforward programming. The power of EJB resides in the fact that it saves a developer the pain of developing a homegrown infrastructure.

This article will focus on the design and development of container-managed entity beans. I will begin with a brief summary of the changes introduced in EJB Specification 1.1 and follow it with a brief tour of session beans before I delve fully into a discussion of entity beans (the fun part).

Improved recipe

EJB Specification 1.1 tightened some of the issues that were loosely defined by Sun Microsystems in version 1.0. These are the changes/modifications, as defined by EJB Specification 1.1:

  1. Mandatory entity-bean support for container providers.
  2. Improved support for EJB environment management, which means the bean provider must specify the bean's entire environment using entries in a JNDI context.
  3. Clear lines of separation between the roles and responsibilities of the bean provider and that of the application assembler.
  4. Removed support of deployment descriptor features that described the deployer's output. Also, the deployment descriptor is specified in XML.
  5. JDK 1.2 caused the EJB container vendors to change their runtime libraries with the Java class java.security.Identity to java.security.Principal interface.
  6. The package name of the javax.jts interface has changed to javax.transaction. Also, modifications were made in the thrown exceptions.
  7. All finder methods must throw the FinderException.
  8. ejbCreate() requires a different value. Instead of void(), ejbCreate() returns the primary key class reference.

As a component developer, you must understand what each bean flavor provides its clients. EJB Specification 1.1 supports both session and entity beans. Before we brew the beans, let's taste each flavor.

Taste session beans

Before tasting the session beans, we must first understand their main ingredient: their sessions. A session represents a conversation instance. And like any conversation, a session exists for a limited period of time. It ends when the thread connecting the conversation dies.

A session bean is a logical extension of the conversation instance, but resides on the server. For its entire life, a session bean exists in the container, which manages security, concurrency, etc. Also, the client view of a session bean does not depend upon location. A session bean presents the same set of APIs to its client, which can be another EJB, a Java applet, a Java application, a Java servlet, or a CORBA client. Whether the client runs in the same Java VM as the session bean is immaterial.

Unlike entity beans (which I will discuss later), session beans do not advertise their identities. Thus, session beans appear to be anonymous to the client. Because of this, when EJBObject.getPrimaryKey() and EjbHome.remove(Object primaryKey) methods are invoked on session beans, you obtain java.rmi.RemoteException. This means component developers should not provide finder methods when writing session beans.

Also, single-client applications (I use the word application loosely) use session beans, which are relatively short-lived and unable to survive an application crash or server restart.

Now that we have tasted session beans, let's savor the power of entity beans.

Taste entity beans

An entity bean represents a component view of the data residing in a persistent storage area, like a database or a flat file. You would usually map a row in a database to an entity bean. For instance, let's say the following employee table resides in a database with the following schema:

   Employee_ID:SMALLINT
   Employee_Name:VARCHAR(50)
   Employee_Address:VARCHAR(50)

The component developer would create an entity bean called EmployeeBean that contained the three attributes present in the employee table. Like session beans, entity beans are server-side components and live within a container. However, unlike session beans, entity beans can endure a server restart or container crash. Also, the container provides various services like security, concurrency, transaction management, and persistence -- in the case of container-managed entity beans.

Different clients can concurrently access each entity bean. The container manages the underlying synchronization of the entity beans' data in a container-managed persistence. In a bean-managed persistence, you must write code to ensure consistent data management. Like session beans, every entity bean offers the same view to its client, irrespective of whether the client runs in the same Java VM. Also like session beans, an entity bean's client can be another bean, a Java applet, a Java application, Java servlet, or even a CORBA client.

A container can manage multiple entity beans deployed within it, and provides a home interface for each deployed bean. An entity bean's home interface provides the bean's client with a set of APIs to create, find, and remove entity bean instances. To create entity bean components, you must implement the following two interfaces over and above the component (i.e. the bean):

  1. The home interface: EJBHome
  2. The remote interface: EJBRemote

Home interface

The entity bean developer creates a home interface, which inherits the javax.ejb.EJBHome interface. Let's look at javax.ejb.EJBHome and the methods an entity bean would have in its home interface:

public interface EJBHome extends Remote
{
  void remove(Handle someHandle) throws RemoteException, RemoveException;
  void remove(Object aPrimaryKey) throws RemoteException, RemoveException;
}

The methods an entity bean would have on its home interface are:

  • Create methods

    Unlike session beans, the EJB specification allows for overloaded

    create()

    methods to create entity beans. Typically, you would pass data as arguments to this method; you could then initialize the entity bean with the needed state when it is created. The specification mandates that the return type of the

    create()

    method return a reference to the

    EJBRemote

    object. Also, the throws clause of every

    create()

    method should have

    java.rmi.RemoteException

    and

    javax.ejb.CreateException

    . However, you have the flexibility to add any application-specific exceptions to the throws clause.

  • Finder methods

    An entity bean's home interface defines one or more finder methods. EJB Specification 1.1 tells you to provide the

    findByPrimaryKey()

    method for entity beans. This method allows a client to look up entity beans by their primary key. The name

    findByPrimaryKey()

    must not change, and it should provide one argument that represents the entity bean's primary key type. The return type of

    findByPrimaryKey()

    must be an entity bean's remote interface. Each finder method should throw

    java.rmi.RemoteException

    and

    javax.ejb.FinderException

    . If you want to provide your own custom finder methods, the specification allows for other methods in addition to

    findByPrimaryKey()

    .

  • Remove methods

    The

    EJBHome

    interface provides several ways for a client application to remove an entity bean object that a client is interacting with. A client attempting to use an entity bean that has been removed would get

    java.rmi.NoSuchObjectException

    .

Now that we have covered some basics, let's look at the primary key and object identity of an entity bean.

The component developer creates a primary key class for each entity bean. Hence, if two entity objects have the same home interface and primary key, they are considered identical. The EJB specification does not mention object equality based on the = = operator. Also, if you compare two object references using the Java API, Object.equals(Object foo), the result is unspecified. The only way to compare object equality is through the isIdentical(EJBObject) API.

According to the EJB Specification 1.1, a primary key class is any class with a legal value type in RMI-IIOP. Generally, a primary key class would be associated with a particular entity bean class. However, you are free to use the same primary key class for multiple entity beans.

Now let's see how the employee entity bean home interface and its corresponding PrimaryKey class might look.

   ////////////////////////////////////////////////////////////////////
   // Employee Entity Bean Home Interface
   ////////////////////////////////////////////////////////////////////
   package com.mandera.entitybeansarticle;
   import javax.ejb.EJBHome;
   import java.ejb.CreateException;
   import java.ejb.FinderException;
   import java.ejb.RemoteException;
   public interface EmployeeHome extends EJBHome
   {
    public Employee create(int employeeID, String name, String  address)
                        throws CreateException, RemoteException;
    public Employee findByPrimaryKey(EmployeePrimaryKey empKey)
                        throws FinderException, RemoteException;
   }
   ////////////////////////////////////////////////////////////////////
   //       Primary Key Class
   ////////////////////////////////////////////////////////////////////
   package com.mandera.entitybeansarticle;
   public class EmployeePrimaryKey implements java.io.Serializable
   {
    public int employeeId;
   }

The EJB specification requires that the instance of PrimaryKey be serializable.

The remote interface

The entity bean's client accesses the entity bean object through its remote interface, which provides the client with a set of business methods. An entity bean's remote interface must extend the java.ejb.EJBObject interface.

The following example illustrates the use of remote interface:

   ////////////////////////////////////////////////////////////////////
   // Employee Entity Bean Remote Interface
   ////////////////////////////////////////////////////////////////////
   package com.mandera.entitybeansarticle;
   import javax.ejb.EJBObject;
   import java.ejb.RemoteException;
   public interface Employee extends EJBObject
   {
     public int getEmployeeID() throws RemoteException;
     public void setEmployeeName(String empName) throws RemoteException;
     public String getEmployeeName() throws RemoteException;
     public void setEmployeeAddress(String address) throws RemoteException;
     public String getEmployeeAddress() throws RemoteException;
   }

Persist an entity bean

EJB Specification 1.1 provides two ways to persist an entity bean: container-managed persistence (a relatively simple technique) and bean-managed persistence.

Container-managed persistence

When using container-managed persistence, the component developer is relieved of writing code to provide a persistence mechanism. The EJB container provider takes on the responsibility instead. However, at the time of deployment, the deployer must give the EJB container's tool a list of fields that must be persisted. In turn, the EJB container generates the corresponding database access calls. The advantage of this approach is that the entity bean is hidden from the type of data storage mechanism. The disadvantage is that the EJB container and its tools must be sophisticated enough to map the entity bean's fields to data sources during the deployment stage. For instance, if you use a relational database, the container must be able to undertake object-to-relational mapping.

Bean-managed persistence

When using bean-managed persistence, the component provider shoulders the responsibility of writing database access calls. From a design perspective, the database access calls can be programmed within the entity bean or can reside in another component, thus encapsulating the entity bean from the persistence mechanism. Because it increases software extensibility, I prefer encapsulating the persistence mechanism in different components rather than within the entity bean. This approach makes it easier for an entity bean to work with any other database or a database with a different schema.

Let's look at sample code for an entity bean with container-managed persistence:

1 2 Page 1
Page 1 of 2