Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Bean Components

An entity bean is composed of the following components:

  • Remote interface. The remote interface defines all the business methods for the bean; for an entity bean, these are usually composed of a set of get/set methods for the bean's attributes.

  • Home interface. The home interface defines the methods used to create entity beans and to locate specific beans; beans can be located (using a finder method) by a specific bean attribute or by a set of methods (custom finders), or all beans can be retrieved (find all).

  • Primary key class. The primary key class contains all fields that comprise the primary key for an entity bean and provides two methods: hash() and equals().

  • Bean class. The bean class provides the implementation for all the entity bean's business methods and some overhead lifetime methods.

In this example, I want to model a stock portfolio for a particular user. A portfolio contains the information shown in Table 1.

Table 1 Portfolio Table

Field

Description

Data Type

pk

Primary key

NUMBER

owner

Owner of the portfolio

VARCHAR

symbol

Stock symbol

VARCHAR

name

Company name

VARCHAR

purchasePrice

Purchase price per share

NUMBER

numberShares

Number of shares owned

NUMBER

recentPrice

Most recent price

NUMBER

Remote Interface

The remote interface defines the business methods for the EJB. Listing 1 shows the remote interface for the portfolio. Note that all the methods are declared as being abstract; this is a requirement defined in the JBoss documentation.

Listing 1 Portfolio Remote Interface (Portfolio.java)

package com.informit.javasolutions.portfolio;

// Import the EJB classes
import java.rmi.RemoteException;
import javax.ejb.*;

/**
 * Entity Bean Remote Interface for the Certificate Object
 */
public interface Portfolio extends EJBObject
{
    public abstract int getPk() throws RemoteException;

    public abstract String getOwner() throws RemoteException;
    public abstract void setOwner( String owner )
           throws RemoteException;

    public abstract String getSymbol() throws RemoteException;
    public abstract void setSymbol( String symbol )
           throws RemoteException;

    public abstract String getName() throws RemoteException;
    public abstract void setName( String name )
           throws RemoteException;

    public abstract float getPurchasePrice() throws RemoteException;
    public abstract void setPurchasePrice( float purchasePrice )
           throws RemoteException;

    public abstract int getNumberShares() throws RemoteException;
    public abstract void setNumberShares( int numberShares )
           throws RemoteException;

    public abstract float getRecentPrice() throws RemoteException;
    public abstract void setRecentPrice( float recentPrice )
           throws RemoteException;

}

The portfolio interface is nothing more than a set of get/set methods for the entity bean's fields. All remote interfaces must extend the javax.ejb.EJBObject interface and declare that all methods can throw java.rmi.RemoteException. Table 2 lists the methods that are inherited by the EJBObject interface.

Table 2 EJBObject Interface

Method

Description

EJBHome getEJBHome()

Obtains the enterprise bean's home interface.

Handle getHandle()

Obtains a handle for the EJB object.

java.lang.Object getPrimaryKey()

Obtains the primary key of the EJB object.

boolean isIdentical(EJBObject obj)

Tests whether a given EJB object is identical to the invoked EJB object.

void remove()

Removes the EJB object.

Home Interface

The home interface defines two categories of methods: create methods and finder methods. Listing 2 shows the PortfolioHome interface.

Listing 2 Portfolio Home Interface (PortfolioHome.java)

package com.informit.javasolutions.portfolio;

// Import the EJB classes
import java.rmi.RemoteException;
import javax.ejb.*;

// Import the Collection classes
import java.util.Collection;

/**
 * Defines the Home interface for the Portfolio EntityBean
 */
public interface PortfolioHome extends EJBHome
{
    /**
     * Create method with all non-nullable fields
     */
    public Portfolio create( int pk,
                             String owner,
                             String symbol )
           throws RemoteException, CreateException;

    /**
     * Create method with all fields
     */
    public Portfolio create( int pk,
                             String owner,
                             String symbol,
                             String name,
                             float purchasePrice,
                             int numberShares,
                             float recentPrice ) 
           throws RemoteException, CreateException;

    /**
     * Find a portfolio by its primary key
     */
    public Portfolio findByPrimaryKey( PortfolioPk pk ) 
           throws RemoteException, FinderException;

    /**
     * Find all portfolios owned by a specified owner
     */
    public Collection findByOwner( String owner ) 
           throws RemoteException, FinderException;

    /**
     * Find all portfolios
     */
    public Collection findAll() throws
           RemoteException, FinderException;

}

All home interfaces must extend the javax.ejb.EJBHome interface (shown in Table 3) and must declare that all methods can throw java.rmi.RemoteException. Furthermore, all create methods must declare that they can throw javax.ejb.CreateException, and all finder methods must declare that they can throw javax.ejb.FinderException.

The only required finder method is findByPrimaryKey(), which returns an instance of the remote interface. Other finder methods are optional and return a collection of remote interface instances; findAll() returns all records in the database and the findByXXX() methods return all records that match a specific field. When using JBoss, you can specify findByXXX(), where XXX is one of the bean's CMP managed fields, and it will generate the code to load those records for you!

Table 3 EJBHome Interface

Method

Description

EJBMetaData getEJBMetaData()

Obtains the EJBMetaData interface for the enterprise bean.

HomeHandle getHomeHandle()

Obtains a handle for the home object.

void remove(Handle handle)

Removes an EJB object identified by its handle.

void remove(java.lang.Object primaryKey)

Removes an EJB object identified by its primary key.

Primary Key Class

The primary key class holds all the fields that comprise the primary key for the bean. In JBoss, this class is not necessary for beans with a single primary key value, and can be specified in the bean's deployment descriptor. It's good practice to develop this class and essential for tables with a primary key that spans multiple columns. Listing 3 shows the portfolio's primary key class.

Listing 3 Portfolio's Primary Key Class (PortfolioPk.java)

package com.informit.javasolutions.portfolio;

/**
 * Primary Key class for the Portfolio Entity Bean
 */
public class PortfolioPk implements java.io.Serializable
{
    /**
     * Holds the primary key
     */
    public int pk;

    /**
     * Creates a new Portfolio Primary Key Object
     */
    public PortfolioPk()
    {
    }

    /**
     * Creates and initializes a new Portfolio Primary Key Object
     */
    public PortfolioPk( int pk )
    {
        this.pk = pk;
    }

    /**
     * From Serializable we must implement the hashCode method
     * and provide a unique id for this class - let's use the
     * primary key, it has to be unique!
     */
    public int hashCode()
    {
        return pk;
    }

    /**
     * See if these objects are the same
     */
    public boolean equals( Object obj )
    {
        if( obj instanceof PortfolioPk )
        {
            return( pk == ( ( PortfolioPk )obj ).pk );
        }

        return false;
    }

}

The primary key class must be serializable (implement java.io.Serializable) and must define two methods: hashCode() and equals() (see Table 4). Furthermore, it must have public attributes for all columns that comprise the bean's primary key; EJB uses introspection and reflection to find a bean's attributes and methods, and imposes the restriction that all CMP attributes must be public.

Table 4 Primary Key Required Methods

Method

Description

boolean equals(Object obj)

Indicates whether some other object obj is "equal to" this one.

int hashCode()

Returns a hash code value for the object.

Bean Class

The bean class is the meat of the EJB; it implements the business methods defined in the remote interface. Listing 4 shows the source code for the Portfolio Bean class.

Listing 4 Portfolio's Bean Class (PortfolioBean.java)

package com.informit.javasolutions.portfolio;

// Import the EJB classes
import java.rmi.RemoteException;
import javax.ejb.*;

// Import the JNDI classes
import javax.naming.*;
import javax.rmi.PortableRemoteObject;

// Import the IO classes
import java.io.*;

// Import the Collection classes
import java.util.*;

public class PortfolioBean implements EntityBean
{
    /**
     * Entity context
     */
    transient private EntityContext ctx;

    /**
     * CMP Managed fields
     */
    public int pk;
    public String owner;
    public String symbol;
    public String name;
    public float purchasePrice;
    public int numberShares;
    public float recentPrice;

    /**
     * Create method - must implement because PortfolioHome defined
     * a create method with this signature returns a PortfolioPk
     * object (as null because we are using container managed
     * persistence - container creates the primary key)
     */
    public PortfolioPk ejbCreate( int pk,
                                  String owner,
                                  String symbol ) {
        this.pk = pk;
        this.owner = owner;
        this.symbol = symbol;

        return null;
    }

    /**
     * Create method with all fields
     */
    public PortfolioPk ejbCreate( int pk,
                                  String owner,
                                  String symbol,
                                  String name,
                                  float purchasePrice,
                                  int numberShares,
                                  float recentPrice ) {
        this.pk = pk;
        this.owner = owner;
        this.symbol = symbol;
        this.name = name;
        this.purchasePrice = purchasePrice;
        this.numberShares = numberShares;
        this.recentPrice = recentPrice;

        return null;
    }


    /**
     * Must have an ejbPostCreate() method matching the signature of
     * each ejbCreate() method - performs any follow-up operations
     */
    public void ejbPostCreate( int pk,
                               String owner,
                               String symbol ) {
    }

    /**
     * Create method with all fields
     */
    public void ejbPostCreate( int pk,
                               String owner,
                               String symbol,
                               String name,
                               float purchasePrice,
                               int numberShares,
                               float recentPrice ) {
    }

    /**
     * Implement the business methods in the Portfolio Remote
     * Interface
     */
    public int getPk() {
        return this.pk;
    }

    public String getOwner() {
        return this.owner;
    }

    public void setOwner( String owner ) {
        this.owner = owner;
    }

    public String getSymbol() {
        return this.symbol;
    }

    public void setSymbol( String symbol ) {
        this.symbol = symbol;
    }

    public String getName() {
        return this.name;
    }

    public void setName( String name ) {
        this.name = name;
    }

    public float getPurchasePrice() {
        return this.purchasePrice;
    }

    public void setPurchasePrice( float purchasePrice ) {
        this.purchasePrice = purchasePrice;
    }

    public int getNumberShares() {
        return this.numberShares;
    }

    public void setNumberShares( int numberShares ) {
        this.numberShares = numberShares;
    }

    public float getRecentPrice() {
        return this.recentPrice;
    }

    public void setRecentPrice( float recentPrice ) {
        this.recentPrice = recentPrice;
    }

    /**
     * Saves the Bean's entity context
     */
    public void setEntityContext( EntityContext ctx ) {
        this.ctx = ctx;
    }

    /**
     * Destroys the Bean's entity context
     */
    public void unsetEntityContext() {
        ctx = null;
    }

    /**
     * Unused EntityBean interface methods
     */
    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void ejbRemove() {}
    public void ejbLoad() {}
    public void ejbStore() {}
}

All EJBs must implement the javax.ejb.EnterpriseBean interface (a marker interface); entity beans implement javax.ejb.EntityBean, which extends javax.ejb.EnterpriseBean, and session beans implement javax.ejb.SessionBean, which also extends javax.ejb.EnterpriseBean. Table 5 shows the methods defined in the javax.ejb.EntityBean interface.

Table 5 javax.ejb.EntityBean Interface Methods

Method

Description

void ejbActivate()

A container invokes this method when the instance is taken out of the pool of available instances to become associated with a specific EJB object.

void ejbLoad()

A container invokes this method to instruct the instance to synchronize its state by loading its state from the underlying database.

void ejbPassivate()

A container invokes this method on an instance before the instance becomes disassociated from a specific EJB object.

void ejbRemove()

A container invokes this method before it removes the EJB object that's currently associated with the instance.

void ejbStore()

A container invokes this method to instruct the instance to synchronize its state by storing it to the underlying database.

void setEntityContext(EntityContext ctx)

Sets the associated entity context ctx.

void unsetEntityContext()

Unsets the associated entity context.

All CMP entity beans must provide publicly accessible attributes for all fields that will be persisted to the database (again this is because of EJB constraints imposed by its use of introspection and reflection). The names of these fields must match the corresponding business methods in the remote interface; for example, if there is a method getOwner() that returns a java.lang.String, there must be a corresponding field owner of type java.lang.String. (Note that this is only required for CMP managed fields—more on that in future articles.)

EJBs implement all the methods defined in the remote interface, but notice that the bean doesn't implement the remote interface directly. The method names will be resolved at deployment time, but because the EJB doesn't implement its remote interface directly it's confusing at first.

EJBs are required to provide an ejbCreate() method with a matching signature to each of the create() methods defined in the bean's home interface, with the exception that instead of returning an instance of the remote interface, it returns an instance of the primary key class. CMP beans are required to return null. Furthermore, each ejbCreate() method must be accompanied by an ejbPostCreate() method.

Finally, notice that the bean is required to provide implementations of all the methods defined in the javax.ejb.EntityBean interface. Most of these methods will be useful when using BMP, so we'll just provide placeholders for now.

Compilation

Place all four of the files from Listings 1[nd]4 in the following package:

com.infomit.javasolutions.portfolio

Recall that the directory structure mimics the package:

com/infomit/javasolutions/portfolio

Using the JDK 1.3, compile these four files with the following files added to your CLASSPATH:

YOUR_JBOSS_HOME/lib/ext/ejb.jar

If you're not using the JDK 1.3, you need to include JBoss's jndi.jar file as well as the Java 2, Enterprise Edition's j2ee.jar.

Deployment

Unlike standard Java applications or applets, EJBs must be deployed to an EJB container. For the EJB container to know the location of the files that comprise the bean and their respective roles, we must develop a deployment descriptor. Listing 5 shows the contents of our deployment descriptor.

Listing 5 Portfolio Deployment Descriptor (ejb-jar.xml)

<?xml version="1.0"?>

<!DOCTYPE ejb-jar PUBLIC
   "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN"
   "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">

<ejb-jar>
  <display-name>StockBeans</display-name>
  <enterprise-beans>

    <entity>
      <description>Represents a Portfolio record in the database
      </description>
      <ejb-name>PortfolioBean</ejb-name>
      <home>com.informit.javasolutions.portfolio.PortfolioHome</home>
      <remote>com.informit.javasolutions.portfolio.Portfolio</remote>
      <ejb-class>com.informit.javasolutions.portfolio.PortfolioBean
      </ejb-class>
      <persistence-type>Container</persistence-type>
      <prim-key-class>com.informit.javasolutions.portfolio.PortfolioPk
      </prim-key-class>
      <reentrant>False</reentrant>

      <cmp-field><field-name>pk</field-name></cmp-field>
    </entity>

  </enterprise-beans>

  <assembly-descriptor>
    <container-transaction>
      <method>
        <ejb-name>PortfolioBean</ejb-name>
        <method-name>*</method-name>
      </method>
      <trans-attribute>Required</trans-attribute>
    </container-transaction>
  </assembly-descriptor>
</ejb-jar>

All deployment descriptors are named ejb-jar.xml and have an <enterprise-beans> tag that defines all entity beans and session beans. Entity beans are defined by an <entity> tag and session beans are defined by a <session> tag. In the portfolio deployment descriptor we have one entity bean, and hence one <entity> tag.

Table 6 describes the deployment descriptor tags used in Listing 5.

Table 6 Deployment Descriptor Tags

Tag

Description

<description>

Describes this entity bean, for use with some GUI deployment applications.

<ejb-name>

Names the bean; this name references this bean elsewhere in the ejb-jar.xml file as well as in custom deployment files.

<home>

Defines the fully qualified name of the entity bean's home interface.

<remote>

Defines the fully qualified name of the entity bean's remote interface.

<prim-key-class>

Defines the fully qualified name of the primary key class.

<ejb-class>

Defines the fully qualified name of the entity bean's bean class.

<persistence-type>

Defines who manages the persistence for this bean; it can be either "Container" or "Bean".

<cmp-field>

Notes all fields that are container managed—if the name of the field directly matches the table column names, you can omit these entries.

<assembly-descriptor>

Defines transactional information that I'll use in later articles when I start talking about JTA, so for now just leave that alone.

Once you have this deployment descriptor and your classes in place, you must package your EJB into a JAR file with the following directory structure:

com/informit/javasolutions/portfolio/Portfolio.class
com/informit/javasolutions/portfolio/PortfolioHome.class
com/informit/javasolutions/portfolio/PortfolioPk.class
com/informit/javasolutions/portfolio/PortfolioBean.class

META-INF/ejb-jar.xml

From the folder that contains your com folder, you can build this JAR file with the following command:

jar cf stock.jar com/informit/javasolutions/portfolio/*.class

                 META-INF/*.xml

This will build a file called stock.jar that contains your entity bean. The last step is to copy this file to JBoss's deploy directory. If you have JBoss running, you can watch its text display show you the deployment; if not, start JBoss by executing its run.bat file from its bin directory and look for your bean! You should see something similar to the following:

...
[J2EE Deployer] Create application stock.jar
[J2EE Deployer] Installing EJB package: stock.jar
[J2EE Deployer] Starting module stock.jar
[Container factory] Deploying:file:/
        D:/jBoss-2.0_FINAL/bin/../tmp/deploy/stock.jar/ejb1006.jar
[Verifier] Verifying file:/
        D:/jBoss-2.0_FINAL/bin/../tmp/deploy/stock.jar/ejb1006.jar

[Container factory] Deploying PortfolioBean

If you see any exceptions, read through them and try to troubleshoot the problem; most errors are fairly easy to interpret and involve a missing file from the JAR file, a misspelling, or a case-sensitivity issue (uppercase versus lowercase).

Test Client

Developing an entity bean isn't going to do you much good unless you have a test client with which to look at the bean. Listing 6 shows a test client for the portfolio bean.

Listing 6 Porfolio Test Client (PortfolioTest.java)

import com.informit.javasolutions.portfolio.Portfolio;
import com.informit.javasolutions.portfolio.PortfolioHome;
import com.informit.javasolutions.portfolio.PortfolioPk;

// Import the EJB classes
import java.rmi.RemoteException;
import javax.ejb.*;

// Import the JNDI classes
import javax.naming.*;
import javax.rmi.PortableRemoteObject;

// Import the Java Collection classes
import java.util.*;

public class PortfolioTest
{
    public static void main( String[] args ) {
        System.setProperty( "java.naming.factory.initial",
                           "org.jnp.interfaces.NamingContextFactory");
        System.setProperty( "java.naming.provider.url",
                            "localhost:1099");

        try {
            // Get a naming context
            InitialContext jndiContext = new InitialContext();
            System.out.println("Got context");

            // Get a reference to the Interest Bean
            Object ref  = jndiContext.lookup( "PortfolioBean" );
            System.out.println("Got reference");

            // Get a reference from this to the Bean's Home interface
            PortfolioHome home = ( PortfolioHome )
              PortableRemoteObject.narrow( ref, PortfolioHome.class );

            // Create an Interest object from the Home interface
            for( int i=1; i<=20; i++ ) {
                Portfolio portfolio = home.create( i,
                                                   "Steve",
                                                   "Symbol " + i );
            }

            // Find our portfolio
            Collection portfolios = home.findAll();
            Iterator i = portfolios.iterator();
            while( i.hasNext() ) {
                Portfolio thisPortfolio = ( Portfolio )i.next();
                System.out.println( "Portfolio " +
                                    thisPortfolio.getPk() +
                                    ": " + 
                                    thisPortfolio.getOwner() +
                                    " = " + 
                                    thisPortfolio.getSymbol() );
            }
        }
        catch( Exception e ) {
            e.printStackTrace();
        }
    }
}

To connect to JBoss's JNDI server, we must set a couple of system properties:

System.setProperty( "java.naming.factory.initial",
                    "org.jnp.interfaces.NamingContextFactory");
System.setProperty( "java.naming.provider.url",
                    "localhost:1099");

The naming factory is the class that JNDI will use to locate JBoss's JNDI server, and the provider URL is the network location of the machine that JBoss is running on. In this example, we're running on the same machine and hence we'll use localhost on the standard RMI port 1099.

Next, we create an instance of the javax.naming.InitialContext class; this uses the system properties we specified to connect to JBoss. To find the bean we're looking for (PortfolioBean), we use the InitialContext's lookup() method; this returns an object reference that we need to resolve to the entity bean's home interface.

NOTE

You may read in many books that you can cast this object directly to the home interface—and this will work in almost all cases—but because EJB can be used with CORBA objects through RMI/IIOP, the object is not necessarily a Java object, and must be "narrowed." The javax.rmi.PortableRemoteObject class provides a static method narrow() that tests to make sure that the conversion is permissible and returns the correct object.

Once we have a reference to the home interface, we can start calling its create and finder methods. This example creates 20 portfolio records and then calls findAll() to look them up and display them. Try playing around with the findByOwner() method and adding some records of your own.

CAUTION

Note that if you run this twice in a row you'll run into problems because we're hard-coding the primary keys—and primary keys must be unique! During subsequent tests, comment out the create calls or dynamically generate your primary keys (more to come in future articles on primary key generation).

When you're tired of using some of the records, you can remove them through the Home interface's remove() method—pass it an instance of the entity bean's primary key class:

home.remove( new PortfolioPk( 1 ) );
  • + Share This
  • 🔖 Save To Your Account