Home > Articles > Programming > Java

📄 Contents

  1. BMP Entity Beans
  2. Prerequisites
  3. BMP Entity Bean Components
  • Print
  • + Share This
From the author of

BMP Entity Bean Components

An entity bean is built from the following components:

  • Remote interface: defines the business methods of the bean

  • Home interface: defines the ways that entity beans can be created and located

  • Primary key class: defines the fields that comprise the primary key of the bean's table

  • Bean Class: the implementation of the entity bean

Remote Interface

The remote interface defines the business methods of the entity bean; the business methods for an entity bean are usually comprised of various get and set methods for the bean's fields. Listing 1 defines the remote interface for the Contact bean.

Listing 1. Contact Remote Interface (Contact.java)

package com.informit.javasolutions.contact;

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

/**
 * Defines the Remote interface for the Contact EntityBean
 */
public interface Contact extends EJBObject
{
  public abstract int getId() throws RemoteException;
  
  public abstract String getName() throws RemoteException;
  public abstract void setName( String name ) throws RemoteException;
  
  public abstract String getAddress() throws RemoteException;
  public abstract void setAddress( String address ) throws RemoteException;
  
  public abstract String getCity() throws RemoteException;
  public abstract void setCity( String city ) throws RemoteException;
  
  public abstract String getState() throws RemoteException;
  public abstract void setState( String state ) throws RemoteException;
  
  public abstract String getZip() throws RemoteException;
  public abstract void setZip( String zip ) throws RemoteException;
  
  public abstract String getPhone() throws RemoteException;
  public abstract void setPhone( String phone ) throws RemoteException;
  
  public abstract String getEmail() throws RemoteException;
  public abstract void setEmail( String email ) throws RemoteException;
}

As you can see, all the business methods are get and set methods for each of the columns in the Contact Table (refer to Table 1), with the exception of the id column; this is the primary key of the table, and we do not want to allow the client to modify a bean's primary key!

Note that this interface is in the com.informit.javasolutions.contact package, so the .java file should be in a similar directory structure:

com/informit/javasolutions/contact/Contact.java

Home Interface

The home interface defines the ways that the bean can be created and located—all the create() and findByXXX() methods. Listing 2 defines the home interface for the Contact bean.

Listing 2. Contact Home Interface (ContactHome.java)

package com.informit.javasolutions.contact;

// 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 Contact EntityBean
 */
public interface ContactHome extends EJBHome
{
  /**
   * Create method with all non-nullable fields
   */
  public Contact create( int id,
              String name,
              String email ) throws RemoteException, CreateException;

  /**
   * Create method with all fields
   */
  public Contact create( int id,
              String name,
              String address,
              String city,
              String state,
              String zip,
              String phone,
              String email ) throws RemoteException, CreateException;

  /**
   * Find a contact by its primary key
   */
  public Contact findByPrimaryKey( ContactPk pk ) throws RemoteException, FinderException;

  /**
   * Find all contacts owned by a specified owner
   */
  public Collection findByName( String name ) throws RemoteException, FinderException;
  
  /**
   * Find all contacts
   */
  public Collection findAll() throws RemoteException, FinderException;
}

The home interface defines two create() methods that have two distinct purposes: One create() method initializes all non-nullable fields, and the other initializes all fields. I made the id, name, and email fields all non-nullable; whereas the other fields may be null (I figured that in this age, people may not have a phone number, but they most assuredly have an email address.) All EJB methods can throw a RemoteException if an error occurs in transit, but create() methods must also throw a CreateException, in case something goes wrong in the creation process.

It then defines the required findByPrimaryKey() finder method; this must be defined in every entity bean. It accepts a reference to the Contact's primary key class: ContactPk that is forthcoming.

It defines two subsequent finder methods: findByName() and findAll(); findByName() returns all rows of Contacts that have the specified name, and findAll() returns all rows from the Contact table. Each finder method must be declared to throw FinderException, in case an error occurs during the find process.

Primary Key Class

The primary key class is a class that defines the fields that comprise the primary key for a bean. In our example, the primary key is nothing more than an integer, so we could make our internal representation an Integer (wrapper class) instead of an int and then specify that class. For completeness, however, I usually create a separate class for this function. Listing 3 defines the primary key class for the Contact entity bean.

Listing 3. Contact Primary Key Class (ContactPk.java)

package com.informit.javasolutions.contact;

/**
 * Primary Key class for the Contact Entity Bean
 */
public class ContactPk implements java.io.Serializable
{
  /** 
   * Holds the primary key
   */
  public int id;

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

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

  /**
   * 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 id;
  }

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

    return false;
  }
}

The primary key class holds the primary key of the Contact table(id), and provides the required methods:

  • Default Constructor: Required when the container creates an instance of the primary key using Class.newInstance(); this creates an instance of a class using the parameterless constructor

  • hashCode(): Returns a unique number that represents this primary key class

  • equals(): Returns a boolean that describes whether or not two primary keys are equal

Bean Class

Finally, the bean class itself; this is where all of the work is done. Table 2 summarizes the methods that must be implemented in the bean class.

Table 2 Bean Class Methods

Method

Description

ejbCreate

There is one ejbCreate() method for every create() method defined in the home interface; it is responsible for inserting a new row into the database

ejbLoad

Responsible for attaining the primary key for the bean from the EntityContext and loading the data for this instance of the bean from the database

ejbStore

Responsible for saving all fields that changed since either the bean has been created or loaded, or the last store, to the database

ejbRemove

Responsible for deleting this entity bean's data from the database

ejbPassivate

Responsible for persisting any data or saving the state of a bean while it is being passivated by the container; our implementation does nothing

ejbActivate

Responsible for rebuilding the state of the bean when it has been activated after it has been passivated; our implementation does nothing

ejbFindByPrimaryKey

Each findByXXX() method defined in the home interface must have a corresponding ejbFindByXXX() method defined in the bean class; it is responsible for verifying that the primary key exists in the database and returning it (the primary key)

ejbFindByName

Responsible for finding all rows in the database that have the specified name and returning their respective primary keys in a Java Collection

ejbFindAll

Responsible for returning a Java Collection of all primary keys for all rows in the Contact table

get/set

All of the get/set methods return or update the values of the bean's fields

The source code listing is too long to print, but Table 3 shows a summary of all the SQL statements in each of the aforementioned ejbXXX() methods. Each statement is a PreparedStatement, and its parameters have been omitted.

Table 3 Bean Class SQL Statements

Method

SQL Statement

ejbCreate

INSERT INTO contact VALUES( ?, ?, ?, ?, ?, ?, ?, ? )

ejbLoad

SELECT * FROM contact WHERE id = ?

ejbStore

UPDATE contact SET name = ?, address = ?, city = ?, state = ?, zip = ?, phone = ?, email = ? WHERE id = ?

ejbRemove

DELETE FROM contact WHERE id = ?

ejbFindByPrimaryKey

SELECT id FROM contact WHERE id = ?

ejbFindByName

SELECT id FROM contact WHERE name = ?

ejbFindAll

SELECT id FROM contact

Refer to the included code for the details of each of these SQL statements, but it is all standard JDBC. The only thing that might lead to confusion is that all the finder methods return references to the primary key classes; findByPrimaryKey() returns one and the others return a Java Collection of primary keys—the container uses these primary keys to construct the objects.

Finally, there is one method that we have to add in order to gain access to the database: getConnection(). getConnection() uses JNDI to look up a JDBC datasource with the name:

java:comp/env/jdbc/InformIT

We will take care of mapping our SQLServerPool that we defined earlier in JBoss to be available in our bean in this manner during deployment. Listing 4 shows the implementation details for the getConnection() method.

Listing 4. Bean class's getConnection() method (ContactBean.java)

/**
 * Returns a connection to our database
 */
private Connection getConnection() throws SQLException
{
  try
  {
   // Get a JNDI Context
   Context jndiContext = new InitialContext();

   // Get a datasource for the database
   DataSource ds = ( DataSource )jndiContext.lookup( "java:comp/env/jdbc/InformIT" );

   // Return a connection to the database
   return ds.getConnection();
  }
  catch( NamingException eNaming )
  {
   throw new EJBException( eNaming );
  }
}

Peruse the rest of the code; it is documented so that you should understand what is going on (or at least what I am trying to accomplish.)

Building

Place all the source code files into the following directory structure:

com/informit/javasolutions/contact
 Contact.java
 ContactHome.java
 ContactPk.java
 ContactBean.java

Modify your CLASSPATH environment variable to include the following JAR files (required by JBoss):

/jboss/lib/jdbc2_0-stdext.jar
/jboss/lib/ext/ejb.jar
/jboss/client/jnp-client.jar
/jboss/client/jboss-client.jar (for later)
/jboss/client/jbosssx-client.jar (for later)

Build your Java files using javac or your favorite IDE:

javac com\informit\javasolutions\contact\*.java

Deploying

After you have the source code built, it is time to deploy your bean! There are two steps: (1) construct the deployment descriptors, and (2) build and deploy the files in a JAR file.

Deployment Descriptors

The contact bean needs two deployment files: ejb-jar.xml and jboss.xml. Listing 5 shows ejb-jar.xml.

Listing 5. Standard 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>Contact Example</display-name>
 <enterprise-beans>
  <entity>
   <ejb-name>ContactBean</ejb-name>
   <home>com.informit.javasolutions.contact.ContactHome</home>
   <remote>com.informit.javasolutions.contact.Contact</remote>
   <ejb-class>com.informit.javasolutions.contact.ContactBean</ejb-class>
   <persistence-type>Bean</persistence-type>
   <prim-key-class>com.informit.javasolutions.contact.ContactPk</prim-key-class>
   <reentrant>False</reentrant>
   
   <!--
    Provide a JNDI link to the InformIT database so that this entity
    bean can access it through the following string:

		java:comp/env/jdbc/InformIT

  	Now it is the responsibility of the EJB Container to map 
	  jdbc/InformIT to the actual JNDI database name.
    -->
   <resource-ref>
     <description>Database connection pool</description>
     <res-ref-name>jdbc/InformIT</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
     <res-auth>Container</res-auth>
   </resource-ref>
  </entity>
 </enterprise-beans>
</ejb-jar>

ejb-jar.xml is the standard deployment descriptor that describes all beans that are contained in a JAR file; it does not change from application server to application server. In our example, we create a reference to an entity bean named ContactBean; we specifiy all of its fully-qualified class names as well as its persistence type: Bean. The persistence type can have one of two values: Bean or Container; use Bean for BMP beans and Container for CMP beans. At the end of the entity section, we create a resource reference to a database connection pool (javax.sql.DataSource) with the name "jdbc/InformIT". This enables us to locate this datasource from the container using the following lookup name:

java:comp/env/jdbc/InformIT

The other deployment file is one specific to JBoss named jboss.xml; it is responsible for the JBoss specific mappings—in this case, we need to map our "SQLServerPool" to "jdbc/InformIT". Listing 6 shows the JBoss specific deployment descriptor.

Listing 6. JBoss Specific Deployment Descriptor (jboss.xml)

<?xml version="1.0" encoding="Cp1252"?>

<jboss>
  <secure>false</secure>
  <container-configurations />

  <resource-managers>
   <resource-manager>
    <res-name>jdbc/InformIT</res-name>
    <res-jndi-name>java:/SQLServerPool</res-jndi-name>
   </resource-manager>
  </resource-managers>

  <enterprise-beans>
    <entity>
	  <ejb-name>ContactBean</ejb-name>
	  <jndi-name>contact/Contact</jndi-name>
  	  <configuration-name></configuration-name>
    </entity>
  </enterprise-beans>
</jboss>

Listing 6 creates a resource manager <resource-manager> that maps the resource name "jdbc/InformIT" to the JNDI resource name "java:/SQLServerPool". This completes the link.

Finally, I added a little code in there to change the JNDI lookup name for the Contact entity bean from "ContactBean" to "contact/Contact". It has just been a naming convention of mine to put related beans into their own namespace and drop the "Bean" part of their name.

Building and Deploying the JAR file

Now that you have your deployment descriptors, and your Java files are all compiled, create a directory named "META-INF" in the same directory that is holding your "com" folder, and place your deployment descriptors in it:

com/informit/javasolutions/contact
 Contact.java
 ContactHome.java
 ContactPk.java
 ContactBean.java
META-INF
 ejb-jar.xml
 jboss.xml

Now, build your JAR file using the following command from a command prompt in the root directory that contains both your com and META-INF folders:

jar cf contact.jar com/informit/javasolutions/contact/*.class META-INF/*.xml

This will produce a file named contact.jar in the same directory. Copy this file to your JBoss deployment directory:

/jboss/deploy
 contact.jar

And start JBoss to deploy your bean:

cd \jboss\bin
run

Watch the JBoss window, and see if your bean deploys correctly; you will see something similar to the following:

[J2EE Deployer Default] Deploy J2EE application: file:/D:/jboss/deploy/contact.jar
[J2EE Deployer Default] Create application contact.jar
[J2EE Deployer Default] install module contact.jar
[Container factory] Deploying:file:/D:/jboss/tmp/deploy/Default/contact.jar
[Verifier] Verifying file:/D:/jboss/tmp/deploy/Default/contact.jar/ejb1001.jar
[Container factory] Deploying ContactBean
[Bean Cache] Cache policy scheduler started
[Container factory] Deployed application: file:/D:/jboss/tmp/deploy/Default/contact.jar
[J2EE Deployer Default] J2EE application: file:/D:/jboss/deploy/contact.jar is deployed.

Test Client

After you have your bean built and deployed, you need to test it! I created a small test client that displays the current contents of the Contact table (findAll()—should be empty), adds four entries to the Contact table (create()), displays the entire contents again (findAll()—should return the four we just created), and then does a query on one of the records we created (findByName()). Listing 7 shows the complete listing for the test client.

Listing 7. Test Client (TestClient.java)

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

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

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

import com.informit.javasolutions.contact.Contact;
import com.informit.javasolutions.contact.ContactHome;
import com.informit.javasolutions.contact.ContactPk;


public class TestClient
{
  public static int id = 1;

  public static int addContact( String name,
                 String address,
                 String city,
                 String state,
                 String zip,
                 String phone,
                 String email ) throws Exception
  {
    try 
    {
      // Get a naming context
      InitialContext jndiContext = new InitialContext();

      // Get a reference to the Contact Bean
      Object ref = jndiContext.lookup( "contact/Contact" );

      // Get a reference from this to the Bean's Home interface
      ContactHome home = ( ContactHome ) 
        PortableRemoteObject.narrow( ref, ContactHome.class );
      
      // Create a new Contact
      int newId = id++;
      home.create( newId,
            name,
            address,
            city,
            state,
            zip,
            phone,
            email );
            
      // Return the new primary key
      return newId;  
    }
    catch( Exception e )
    {
      e.printStackTrace();
      throw e;
    }
  }
  
  public static void showContacts() throws Exception
  {
    try 
    {
      // Get a naming context
      InitialContext jndiContext = new InitialContext();

      // Get a reference to the Contact Bean
      Object ref = jndiContext.lookup( "contact/Contact" );

      // Get a reference from this to the Bean's Home interface
      ContactHome home = ( ContactHome ) 
        PortableRemoteObject.narrow( ref, ContactHome.class );
    
      // Find all Contacts
      Collection contacts = home.findAll();
      Iterator i = contacts.iterator();
      System.out.println( "Contacts" );
      while( i.hasNext() )
      {
        Object obj = i.next();
        Contact contact = ( Contact )
          PortableRemoteObject.narrow( obj, Contact.class );
        System.out.println( "\t" + 
                  contact.getId() + ", " +
                  contact.getName() + ", " +
                  contact.getAddress() + ", " +
                  contact.getCity() + ", " +
                  contact.getState() + ", " +
                  contact.getZip() + ", " +
                  contact.getPhone() + ", " +
                  contact.getEmail() );
      }  
    }
    catch( Exception e )
    {
      e.printStackTrace();
      throw e;
    }
  }
  
  public static void showContactByName( String name ) throws Exception
  {
    try 
    {
      // Get a naming context
      InitialContext jndiContext = new InitialContext();

      // Get a reference to the Contact Bean
      Object ref = jndiContext.lookup( "contact/Contact" );

      // Get a reference from this to the Bean's Home interface
      ContactHome home = ( ContactHome ) 
        PortableRemoteObject.narrow( ref, ContactHome.class );
    
      // Find all Contacts
      Collection contacts = home.findByName( name );
      Iterator i = contacts.iterator();
      System.out.println( "Contacts with name: " + name );
      while( i.hasNext() )
      {
        Object obj = i.next();
        Contact contact = ( Contact )
          PortableRemoteObject.narrow( obj, Contact.class );
        System.out.println( "\t" + 
                  contact.getId() + ", " +
                  contact.getName() + ", " +
                  contact.getAddress() + ", " +
                  contact.getCity() + ", " +
                  contact.getState() + ", " +
                  contact.getZip() + ", " +
                  contact.getPhone() + ", " +
                  contact.getEmail() );
      }  
    }
    catch( Exception e )
    {
      e.printStackTrace();
      throw e;
    }
  }

  public static void main( String[] args )
  {
    try
    {
      // Initialize the JBoss settings
      System.setProperty( "java.naming.factory.initial", 
                "org.jnp.interfaces.NamingContextFactory");
      System.setProperty( "java.naming.provider.url", 
                "localhost:1099");

      // Display our contacts
      showContacts();

      // Add some contacts to the database
      addContact( "Steve Haines", "123 Some Street", "Irvine", 
            "CA", "92614", "(949)555-1212", "lygado@yahoo.com" );
      addContact( "Linda Haines", "123 Some Street", "Irvine", 
            "CA", "92614", "(949)555-1212", "mywife@home.com" );
      addContact( "Michael Haines", "123 Some Street", "Irvine", 
            "CA", "92614", "(949)555-1212", "newbaby@here.com" );
      addContact( "InformIT Reader", "123 Some Other Street", "Indianapolis", 
            "IN", "11111-111", "(949)555-1212", "reader@informit.com" );
          
      // Display our contacts again
      showContacts();
    
      // Show Steve's record
      showContactByName( "Steve Haines" );
}
    catch( Exception e )
    {
      e.printStackTrace();
    }
  }
}  

It should be noted that this test client is coded to run once; if you try to run it multiple times, you will get an exception about the creation of multiple beans with the same primary key. If you want to run it multiple times, comment out the addContact() method calls.

Summary

Whew, that was quite an ordeal! Hopefully, now you have an appreciation for all that the containers do for you in CMP beans!

We created, deployed, and tested a BMP entity bean; and you learned about the responsibilities you have when the EJB container notifies you of specific events. It should now be apparent that although we took a trivial example and used BMP to implement it, it would not be hard to take a more sophisticated problem and represent it in BMP. Because you have to do all the work, your queries are not limited to a specific table in the database—or to a database at all; you could have read the information from a proprieraty server or from a file system.

What's Next?

In the next article, we will delve back into the session bean realm and talk about stateless session beans. Happy coding!

  • + Share This
  • 🔖 Save To Your Account