C H A P T E R  6

Developing BMP Entity Beans

The previous two chapters covered the development of entity beans that delegate their persistence management to the EJB container. This chapter discusses how to create and work with entity beans that contain all the code needed to manage their own persistence, that is, bean-managed persistent (BMP) beans. There are many similarities between the development of CMP beans and BMP entity beans; this chapter focuses mainly on the differences.

The Sun ONE Studio 5 IDE provides wizards that let you create the classes required for any BMP entity bean: a bean class, remote or local interfaces or both, and sometimes a primary-key class. To start with, the EJB Builder wizard automates the task of creating a BMP entity bean's infrastructure.

When programming entity beans, you have many options in addition to those described in this chapter. Although this IDE is designed to take care of generating your beans' required classes and method declarations, it flexibly supports many options and leaves many decisions up to you. For more information, refer to the resources listed in Before You Read This Book, or to one of the many excellent texts on programming enterprise beans.


Deciding on an Approach

You can take several approaches to creating entity beans in the IDE. However, you get the most comprehensive support and, in general, the fastest path to bean completion, if you use the approach recommended in Using the EJB Builder With CMP Entity Beans. This methodology takes full advantage of the IDE's ability to ensure consistency and its adherence to the J2EE standard.

If you're not sure whether your entity bean needs to manage its own persistence, look at TABLE 4-1.


Building a BMP Entity Bean

The EJB Builder wizard generates your BMP entity bean's default classes. However, the wizard makes no assumptions about how you want your BMP entity bean to interact with a database. The initial process of setting up the default classes can, therefore, be very brief. To create a BMP entity bean, you take the following steps:

1. Select or create a package to contain the BMP entity bean.

2. Use the EJB Builder wizard to generate the infrastructure of your BMP entity bean.

3. As appropriate, add a primary-key class to the bean.

4. As appropriate, add create, business, home, and finder methods to the bean's code.

5. Complete the bodies of the methods you added.

6. Write all persistence code. Complete any methods that affect data in the database.

The basic steps are discussed next.

Creating a Package

If you need to create a package to house your session bean, do as follows:

1. In the IDE's main window, if the Explorer is not already open, choose View right arrow Filesystems to open the Explorer window to the Filesystems tab.

2. In the Filesystems tab of the Explorer, select a filesystem, right-click, and choose New right arrow All Templates.

The New wizard opens the Choose Template page.

3. Select Java Package and click Next.

The wizard displays the New Object Name page.

4. Type a name for the package and click Finish.

The new Java package appears under your filesystem node.

Starting the EJB Builder Wizard

When you're ready to create a BMP entity bean, do as follows:

1. In the IDE's main window, if the Explorer is not already open, choose View right arrow Filesystems to open the Explorer window to the Filesystems tab.

2. In the Filesystems tab, select the Java package where you want your BMP entity bean to reside.

3. Right-click the package and choose New right arrow All Templates.

The New wizard displays the Choose Template page.

4. Expand the J2EE node, choose BMP Entity EJB, and click Next.

The New wizard displays the BMP Entity Bean Name and Properties page. Notice that the panel on the left shows the current step and the steps you still must complete.

Generating a BMP Entity Bean's Infrastructure

In the BMP Entity EJB page of the wizard, do as follows:

1. Type a name for your BMP entity bean.

2. Decide whether to give your BMP entity bean only a local interface (the default), only a remote interface, or both.

If necessary, you can change the package location of the bean.

3. Click Next. (Or, if you like, skip to the next step.)

The BMP Entity Bean Class Files page shows the class files that will be generated for your BMP entity bean. If necessary:

4. Click Finish when you're done.

The wizard generates the default classes of your BMP entity bean. These classes are discussed next.


Looking at a BMP Entity Bean's Classes

For a BMP entity bean, the EJB Builder wizard generates all the required entity bean classes and sets up communications between them. However, you must code all the persistence logic yourself.

In the Explorer's Filesystems tab, a BMP entity bean has the same appearance as a CMP entity bean, except that when you pause the cursor over the bean's logical node, the tool tip says BMP entity bean logical node.

The nodes marked with the class icon Class icon. represent actual classes, while the one marked with the coffee-bean iconBean icon. is a logical node. Do all your editing in the logical node.

A BMP entity bean's classes implement the same interfaces as a CMP entity bean's classes. However, a BMP entity bean's class is defined as public and not abstract.

Expanding the Nodes

When you expand the nodes under your BMP entity bean's package node, you see something like the tree view in FIGURE 6-1. In this case, the bean has been assigned local-type interfaces. Notice that a BMP entity bean can have no select methods.

 FIGURE 6-1 Explorer's Detailed View of a BMP Entity Bean

Screenshot showing the expanded nodes of a BMP entity bean in the Explorer window. [ D ]

If you generated a primary-key class, it shows up in the Explorer as another major node.

Reviewing the Generated Classes

The EJB Builder wizard adds several default methods to every entity bean.

findByPrimaryKey Method

The method signature findByPrimaryKey is added automatically to your BMP entity bean's home interface, as shown in the following example:

public Account.customer findByPrimaryKey(java.lang.String aKey) 
	throws javax.ejb.FinderException, 
	java.rmi.RemoteException; 

Because this is a BMP entity bean, the wizard adds that method's counterpart, ejbFindByPrimaryKey, to the bean class:

public java.lang.String ejbFindByPrimaryKey(java.lang.String 
	aKey) {
} 

A BMP Entity Bean's Life-Cycle Methods

The wizard adds default life-cycle methods to the bean class of your BMP entity bean, as shown in CODE EXAMPLE 6-1.

CODE EXAMPLE 6-1 Default Life-Cycle Methods of a BMP Entity Bean
public void setEntityContext(javax.ejb.EntityContext aContext) {
	context=aContext;
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbRemove() {
}
public void unsetEntityContext() {
	context=null;
}
public void ejbLoad() {
}
public void ejbStore() {
}

The purposes of these methods in a BMP entity bean are described in TABLE 6-1. (For comparison, see TABLE 4-2.)

TABLE 6-1 Purpose of Default Life-Cycle Methods in a BMP Entity Bean Class

Method

Purpose

setEntityContext

This method lets you store the EntityContext reference in a field and populate nonpersistent fields. You can use it to allocate resources that are independent of the EJB object and last for the entity bean's lifetime, resources such as a database-connection factory. By default, the EJB Builder wizard generates code that assigns the EntityContext to a field named context.

ejbActivate

This method initializes the bean, prepares it for use, and acquires the resources needed by the instance.

ejbPassivate

Before the bean instance is returned to the generic instance pool, this method releases the resources the bean was using.

ejbRemove

In a BMP, this method executes SQL Delete statements and removes data from the underlying data storage. Or, you can call another object, such as a DAO, to remove data.

unsetEntityContext

This method lets you deallocate resources and release memory used by the entity bean instance, before the container destroys the instance.

ejbLoad

In a BMP, this method executes SQL Select statements and loads data into the bean instance from the underlying data source. This happens when the bean is activated or when the entity is referenced within the context of a new transaction. Or, you can call another object, such as a data access object (DAO), to load data.

ejbStore

In a BMP, this method executes SQL Update statements and saves the bean's state (the current values in the persistent fields) to the underlying data storage. This happens when the bean is passivated or when the transaction is committed. Or, you can call another object, such as a DAO, to store data.



Completing Your BMP Entity Bean

To complete your BMP entity bean, do as follows:

  • Add all persistence logic.
  • Add a primary key class if your BMP entity bean has a composite primary key.
  • Define a create method if you want clients of your bean to be able to insert data into the database. An entity bean can have more than one create method.
  • Define any finder methods that your BMP entity bean needs besides findByPrimaryKey, and code the bodies of all the finder methods.
  • Code the ejbRemove method to remove the appropriate record from the database.
  • Define and code all business and home methods that your BMP entity bean needs.
  • Add private fields to maintain your entity's state in memory and populate the values of these fields.

Using Recommended Approaches When Working With Enterprise Beans

Appendix A discusses the best ways to make changes in your enterprise beans, and the errors and anomalies that you might see if you use other approaches. As a general rule, you should work through the logical node rather than the individual class nodes, use the bean's property sheets or the Customizer dialog box to edit methods, and use the IDE's Source Editor to complete or edit any bean code that isn't available to you through one of the dialog boxes.

Adding Persistence Logic

To make your BMP entity bean interact with the entity data store, you must write code to access the data, manipulate persistent fields, and transfer data between your bean instance's variables and the data store. Use the Source Editor to write your code. Use resource references (as discussed in Chapter 8) to specify the data source that your bean will use.

Adding a Primary-Key Class

Use the Source Editor to add a primary-key class if:

  • You didn't create a primary-key class when you created the BMP entity bean, and your bean needs one.
  • You need to specify a primary key that can't be represented by any existing class.
  • Your primary key has a type other than java.lang.String or an existing primary-key class.
  • You must customize the definition of the equals and hashcode methods.
  • You want to wrap the primary key with some extra functionality, such as testing the key for valid values before it is used with the database.

Make sure your primary-key class meets the following requirements:

  • The class has the access-control modifier public.
  • All fields are declared as public.
  • The class has a public default constructor.
  • The class implements the hashCode and equals methods.
  • The class is serializable: It implements the java.io.Serializable interface.
  • The class does not implement the java.rmi.Remote interface.

For more information, see the discussion in Adding or Replacing a Primary Key.

Adding Methods

To start defining a new methods, go to the Explorer, right-click the logical bean node, and take advantage of the GUI tools that are available from the contextual menu. Use the dialog boxes to name a method and define its signature. The IDE propagates your method automatically to the correct classes. Then finish coding your method within the Source Editor.

Defining Create Methods

The home interface of your BMP entity bean can have a create method, and, if so, the bean class must have corresponding ejbCreate and ejbPostCreate methods. When you use the recommended process, the IDE ensures that these methods are generated and propagated correctly.

The ejbCreate method in a BMP entity bean typically does the following:

1. Validates client-supplied arguments

2. Initializes the instance's variables

3. Executes SQL Insert statements (or you can call another class, such as a DAO, to insert data into the underlying data store)

4. Returns a primary key

In a BMP entity bean, you must provide the code that generates and executes the necessary SQL Insert statement.

The ejbPostCreate method, which the IDE adds automatically, gives the programmer the opportunity to forward information about the EJB object (such as the home or remote interface) to any other enterprise beans that need to reference it. The method can access the remote interface through EntityContext, which it receives from the container as a parameter. This method is typically used to create dependent beans. For example, the Order bean's ejbCreateLineItem method might create the given line items in the ejbPostCreate method.

Your entity bean can have more than one create method. Define a new create method as follows:

1. Select the logical node, right-click, and choose Add Create Method.

The Add New Create Method dialog box appears.

2. Name your create method, using any extension after create.

Now you need to add parameters to your method.

3. In the dialog box, click Add.

4. In the Enter Method Parameter dialog box, specify the parameter's name and type.

Both the method signature in a BMP entity bean class and the method body return the primary-key type.

5. Click OK to dismiss the Enter Method Parameter dialog box.

6. In the Add New Create Method dialog box, specify any additional exceptions.

7. Click OK to dismiss the Add New Create Method dialog box.

The method you added now appears in the bean class code as ejbCreate and in the home interface as create. The method ejbPostCreate also appears in the bean class.

8. Use the Source Editor to add the return statement and all other necessary code to your new create method.

Adding Finder Methods

The EJB Builder has already generated a default finder method for you. In a BMP entity bean, this method shows up in both the home interface (findByPrimaryKey) and the bean class (ejbFindByPrimaryKey). However, if you want your entity bean to execute additional queries, you must define additional finder methods.

If you follow these steps, your new finder method is automatically propagated to your home interface and bean class:

1. Select the logical node, right-click, and choose Add Finder Method.

2. Type a name for the method starting with find. Specify parameters, exception, and a return type. Click OK when you're finished.

Finish coding your finder method or methods using the Source Editor. To fetch primary keys from the data source, you must write JDBC code or use other means of database access.

Defining Business and Home Methods

To add a business method to your BMP entity bean, do as follows:

single-step bulletUnder the logical node, select Business Methods, right-click, and choose Add Business Method.

The Add New Business Method dialog box appears. At this point you can finish coding the method's parameters and exceptions in this dialog box, or you can simply type a name for your new business method, click OK, and finish the coding in the Source Editor.

A business method typically accesses and modifies the values of persistent fields, but it doesn't directly access the database. The EJB container calls the ejbLoad and ejbStore methods as required by the semantics of the transaction.

Alternatively, you can add a home method to perform an operation that does not depend on any given instance of the entity bean. See Defining Home Methods for a discussion of home methods.


After Creating Your BMP Entity Bean

Your BMP entity bean is now finished except for a few steps by which you prepare the bean to work in its eventual environment. These final steps are described in Chapter 8.

Recommendations for working with finished enterprise beans are given in Appendix A.


Further Reading

Enterprise beans can be a very powerful and flexible part of your application. Creating the basic parts of an enterprise bean can be very simple, especially with a tool like the Sun ONE Studio 5 IDE. However, completing the bean so that it fulfills the needs of your application can be very complex. For details, refer to Enterprise JavaBeans Specification, version 2.0 at:
http://java.sun.com/products/ejb/docs.html

The J2EE Tutorial contains useful advice for developing BMP entity beans. Go to http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/BMP.html for examples and instructions.

You might also refer to Advanced Programming for the Java 2 Platform by Calvin Austin and Monica Pawlan at: http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/bmp3.html