C H A P T E R  4

Developing CMP Entity Beans

The EJB Builder in the Sun ONE Studio 5 IDE enables you to program the entity beans you need to represent data in your J2EE application. This chapter focuses on how you develop individual entity beans whose persistence is managed by the EJB container, or CMP entity beans.

The IDE provides wizards that let you create the classes required for an Enterprise JavaBeans component (enterprise bean): a bean class, interfaces (local, remote, or both), and sometimes a primary-key class. Much of the task of creating these classes is automated for you.

When programming entity beans, you have many options in addition to those described in this chapter. Although the IDE is designed to take care of much of your coding work, it also supports those options flexibly 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.


Using the EJB Builder With CMP Entity Beans

The EJB Builder is a collection of wizards, property sheets, and editors with which you can build enterprise beans consistently and easily. This tool is installed automatically with the IDE, and it becomes visible when you choose File right arrow New from the main window or New right arrow All Templates from the contextual menu in the Explorer's Filesystems tab.

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 this chapter. You can also use the example applications and tutorials, available from the main window's Help right arrow Learning menu, to explore different ways of creating enterprise beans. The methodology described in these documents takes full advantage of the IDE's ability to ensure consistency and its adherence to the J2EE standard.

For best results, use the EJB Builder to program entity beans by:

The logical node is the best place from which to work with an entity bean. All logical nodes appear in the Explorer with this icon:Logical node icon.

From an entity bean's logical node, you can add methods that are automatically placed in the appropriate classes, add fields, validate the entire bean, specify deployment-related properties for the bean, build a test application for the bean, and create an EJB module to facilitate the bean's deployment in a production application.


Comparing CMP and BMP Entity Beans

Before you begin creating an entity bean, first consider whether to use CMP or BMP. The IDE's EJB Builder supports either type of entity bean, but you use different processes to create each of the two types. A more detailed discussion of this choice is in Chapter 2. Here, TABLE 4-1 highlights the design considerations.

TABLE 4-1 Deciding Between CMP and BMP Entity Beans

Issue

CMP

BMP

Relationship with the database

A CMP entity bean depends on its container to manage its relationship with a database, and is not dependent on any particular data store.

A BMP entity bean handles its own relationship with a specified database.

Persistence

The container manages database access for this and every other CMP entity bean in the application. The bean code does not include calls to the database. The bean's persistent state is represented by virtual persistent fields.

A BMP entity bean contains all the code connecting it to a specified database. A BMP entity bean with persistent data (coded as instance variables) also must contain all necessary calls to the database. All SQL code must be added by hand. If your EJB container doesn't provide adequate persistence mapping to the data store, you must create a BMP entity bean.

Process

The basic structure of a CMP entity bean (the default classes) is simpler and quicker to create. Less coding is needed.

A BMP entity bean requires more coding, which might be an attractive option for experienced JDBC programmers.

Design scope

A single CMP entity bean normally represents only one table, but a bean can be mapped to two or more tables.

A BMP entity bean can be hand-coded to represent one or more tables.

Power and flexibility

A CMP entity bean depends on its container for access to a database, but this bean can be deployed in many different database environments.

An individual BMP entity bean is manually programmed for database access. A BMP entity bean works only in the environment for which it was written.


The rest of this chapter addresses how to create CMP entity beans and issues to consider during development. For the process of creating BMP entity beans, see Chapter 6.


Creating Sets of Related CMP Entity Beans

Many J2EE applications contain related CMP entity beans. That is, two CMP entity beans can have a relationship that is represented by a container-managed relationship (CMR) field. This relationship is analogous to the situation in a database or database schema when two entities or tables contain a related column. For example, a schema might include the tables Customer, Order, LineItem, and Part. The Order table has a foreign key to the Customer table, LineItem has a foreign key to Order, and LineItem also has a foreign key to Part.

The IDE makes it easy to create a whole set of related CMP entity beans at once. When you use the EJB Builder wizard to generate a set of CMP entity beans to manipulate related database entities, the wizard recreates the entities' relationships in your CMP entity beans, and lets you specify additional relationships between beans. These relationships are represented in a CMP entity bean as CMR fields, and they can be edited for cardinality, type, and cascade-delete capability.

If you want to create a set of related CMP entity beans, or if you want to preserve foreign-key relationships between two entity beans, see Chapter 5.


Defining a CMP Entity Bean

The EJB Builder wizard automates much of the task of creating the minimum classes that your CMP entity bean requires: a bean class, and the interfaces you choose (local, remote, or both local and remote). If you specify a composite primary key, or if a table you chose requires a composite primary key, the wizard also creates a primary-key class for you. To define a CMP entity bean, you take the following steps:

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

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

3. As appropriate, add create, finder, home, select, and business methods to the bean.

4. Complete the bodies of the methods you added.

5. If necessary, add a primary-key class.

These basic steps are explained in detail 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.

Having a Data Source Ready

A CMP entity bean is modeled on an actual table from a database, and the bean's persistent fields echo the table's columns. Using the EJB Builder Wizard, you can obtain the table from a live database connection or a database schema object (a snapshot of one or more tables of a database). Or, in one of the wizard's pages, you can manually specify a database table's columns as your bean's persistent fields, and then at deployment the fields can be mapped to the actual database columns.

Notice that EJB containers vary in how they treat column-to-field mappings. The PointBase database server is included with the IDE, automatically loaded during the IDE's installation, and represented in the following examples. If you're using another database server with the IDE, refer to its documentation for details.

Consider the following when deciding which form of data source to use:



Note - Before you start the IDE, make sure that the s1studio-install-directory/ lib/ext directory contains the driver files for any database that was not automatically loaded when the IDE was installed. This is the only way to ensure that you can select the right database driver when creating your new schema. You can't mount the driver files in the Explorer or place the driver files in the CLASSPATH env variable. Refer to the Sun ONE Studio 5, Standard Edition Getting Started Guide for details.



Starting: To start the PointBase database, choose Tools right arrow PointBase Network Server right arrow Start Server from the main window.
Connecting: To connect to the running PointBase database, go to the Runtime tab of the Explorer. Expand the Databases node. Select the node whose label begins with jdbc:pointbase:server and whose icon appears broken in two. Right-click the node and choose Connect. The PointBase icon becomes whole, and you can expand the node to see the database tables, views, and procedures.
This is the best way to connect to the database, especially if you're going to be creating more than one entity bean. Alternatively, you can start the database before you start the EJB Builder Wizard, and then you can connect to the database from within the wizard. However, if you do that, you must reconnect for every entity bean you create.
If you're using a database that is installed but not yet connected, the EJB Builder wizard lets you connect during the process of creating a new CMP entity bean. See Selecting a Table From a Database Connection.

Starting the EJB Builder Wizard

When you're ready to create a single CMP 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 new CMP 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 CMP Entity EJB, and click Next.

The New wizard displays the CMP Entity Bean Name and Properties page. Notice that the panel on the left shows the current step and the steps you still must complete to generate the infrastructure of your CMP entity bean.

Generating a CMP Entity Bean's Infrastructure

In the EJB Builder`s CMP Entity Bean Name and Properties page, as shown in FIGURE 4-1, you name your CMP entity bean. Here, you also make choices about where your bean will get its persistent fields and which kinds of interfaces your bean will have. You can also change the bean's package location, if you like.

 FIGURE 4-1 Selections in the EJB Builder Wizard for CMP Entity Beans

Screenshot showing the wizard's first pane and selections for a CMP entity bean. [ D ]

The following tables describe these selections and point to your next instructions in this chapter.

In the radio-button box labeled Source for Entities and Fields, consider the following selections.

Table From Database Connection

Select this if your CMP entity bean will represent a table from an existing database. If you leave the EJB Name field blank (<default>), the wizard assigns the bean the the same name as the database table.

See Selecting a Table From a Database Connection.

Table From Database Schema Object

Select this if you have a database schema available, and you don't want to connect to a live database. Again, you can use the default EJB name if you want to make the table-to-bean correlation obvious.

See Selecting a Table From a Database Schema Object.

CMP 2.x Bean Class

Select this if your CMP entity bean will be based on an existing bean class that follows the EJB 2.0 specification.

See Using a CMP 2.x Bean Class.

CMP 1.x Bean Class

Select this if your CMP entity bean will be based on an existing bean class that follows the EJB 1.x specification.

See Using a CMP 1.x Bean Class.

Create From Scratch

Select this if you will specify all the CMP fields yourself.

See Creating Your Bean's Persistent Fields From Scratch.


In the radio-button box labeled Component Interfaces, consider the following selections.

Remote Interface Only

Select this if an external client calls methods on your CMP entity bean, and your bean is never called by local clients.

Local Interface Only (Default)

Leave this selection active if your bean is called only through its local interfaces, never directly by an external client.

Both Remote and Local Interfaces

Select this if your bean is called by both external and local clients (which can also be other beans).


When you have made your selection and clicked Next, the wizard presents appropriate follow-up tasks, which are described next.

Specifying Persistent Fields From a Database Table

If you have chosen to specify persistent fields from a database, you must already be connected to a live database or have an existing database schema object available. For more information, see Having a Data Source Ready and Capturing a Database Schema. The EJB Builder wizard maps columns from a table of the database (Table from Database Connection) or from a schema (Table from Database Schema Object) to create your entity bean's persistent fields. Both choices provide the same result in your finished entity bean.

Most application servers let you map a bean's CMP fields to database columns at deployment time. The server then dynamically generates SQL statements for that mapping within the server process.

Selecting a Table From a Database Connection

If you have direct access to the database itself, and if contention among database users is not a problem, you might want to use the direct database connection. (If you need to start and connect to a database, see Having a Data Source Ready.)

You should now be in the wizard's Table from Database Connection page. The databases to which you can connect your entity bean appear in the wizard page's tree view. Do as follows:

1. Select a database.

Depending on the status of the database, use one of the following approaches.

a. Select the database from the Name combination box.

b. Check the Driver field to make sure the path is correct.

c. Specify the required information in the Database URL field.

d. Supply a user name and password if any are needed for your database.

e. Check the Remember Password During This Session box if appropriate.

f. Click OK. In the wizard's Table from Database Connection page, click Next.

The connection becomes available.

a. Select the database and click Connect to Database.

The broken halves become a whole icon.

b. Expand the database node and the Tables sub-node.

If you get an Unable to connect error message, make sure that the database is up and running.

2. Descend through the selected database's hierarchy until you see a node for the table that you want to map to your bean. Select a table and click Next.

You see the CMP Fields page, displaying side by side the columns in your database table and the corresponding fields that the EJB Builder Wizard will create in your new CMP entity bean. The wizard will map those database columns to your bean's persistent fields.

3. Check the Java field names and types, and make any necessary changes.

The IDE has assigned default names and types to your Java fields. You can change the names and types if necessary, selecting a field and clicking the Edit button to see other permissible data types.

For more information, refer to Chapter 8, "Mapping SQL and Java Types" of Getting Started with the JDBC API. You can find the document at:

http://java.sun.com/j2se/1.4.1/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html

4. Click Next. (Or, if you don't want to examine or change the default classes that the wizard assigns, skip this step and click Finish.)

The CMP Entity Bean Class Files page of the wizard appears, listing the parts of your entity bean's infrastructure: the bean class, the interfaces you chose (local, remote, or both), and the type of the primary-key class.

In this page, you can accept or change your bean's classes. The wizard lets you specify another bean class, interface, or primary-key class if you wish. As you see if you click one of the Modify buttons, you can specify another package for the class or interface to reside in or to come from.

However, first you should find out whether the application server you plan to use supports this distribution of files.

5. Click Finish.

Your CMP entity bean's infrastructure is generated automatically by the EJB Builder. See Looking at a CMP Entity Bean's Classes for more discussion.

Capturing a Database Schema

You might need to build your CMP entity bean on a table from a database schema rather than connecting directly to the database. If you don't already have a schema, you can use the IDE's Database Schema wizard to create one. First, if you need to start and connect to a database, see Having a Data Source Ready. Then do as follows:

1. In the IDE, open the Database Schema wizard in one of the following ways:

Both of these wizard pages give you the same end result.

2. As directed by the wizard, specify the database to be used and select the tables to be included in your schema.

You can give your database schema a name, or the wizard automatically names it DatabaseSchema.

The IDE reads table definitions from the database to create the schema. A progress bar shows the number of tables and views captured. The resulting schema object appears under the package node you specified.

Selecting a Table From a Database Schema Object

If database access is restricted but schema objects have been made available, you might want to build your CMP entity bean using a table from a schema. (If you don't have a schema available and need to create one, see the foregoing section.)

Having selected Table from Database Schema Object on the first page of the wizard, you should now be in the Table from Database Schema Object page. The directories that have been mounted in the Explorer's Filesystems tab appear in the wizard page. Do as follows:

1. Locate the database schema that contains the table on which you will build your bean.

Descend through the selected schema's hierarchy until you see a node for the table that you want to map to your bean.

2. Expand the schema's nodes until you find the table you want to use. Select the table.

The Next and Finish buttons become active.

3. Click Next to review the database columns that will be mapped to your bean's persistent fields. (Or, click Finish to skip this step and the next, and have the wizard generate your bean's infrastructure.)

The CMP Fields page appears, displaying side by side the columns in your database table and the corresponding fields that the EJB Builder will create in your entity bean. You can change field names and types if necessary, selecting a field and clicking the Edit button to see other permissible data types.

4. Click Next to examine or change the default classes that the wizard assigns. (Or, click Finish to skip this step and have the wizard generate your bean's infrastructure.)

The CMP Entity Bean Class Files page of the wizard appears, listing the parts of your entity bean's infrastructure: the bean class, the interfaces you chose (local, remote, or both), and the type of the primary-key class.

In this page, you can accept or change your bean's classes. The wizard lets you specify another bean class, interface, or primary-key class if you wish. As you see if you click one of the Modify buttons, you can specify another package for the class or interface to reside in or to come from.

However, first you should find out whether the application server you plan to use supports this distribution of files.

5. Click Finish.

Your CMP entity bean's infrastructure is generated automatically by the EJB Builder See Looking at a CMP Entity Bean's Classes for more discussion. .

Using a CMP 2.x Bean Class

You might want to base your new CMP entity bean on an existing CMP entity bean that was created in the EJB 2.0 environment. In the wizard's CMP Entity Bean Name and Properties page, you select CMP 2.x Bean Class and click Next. The wizard then presents a navigation list from which you pick a bean class.

You should now be in the Select a CMP 2.x Bean Class page. Do as follows:

1. Navigate to the bean class you want to use, and select the class.

Notice that the IDE presents only the bean class for selection, not the other elements of the bean. When you have selected the class, the Next button is enabled.

2. Click Next.

The IDE presents the fields of the bean class you selected. Even if the original CMP entity bean had a primary key, in this page you must designate one or more fields as the primary key.

3. Select the field that should be the primary key and click Edit.

The Edit Persistent Field dialog box appears.

4. Make any necessary changes, including checking the Primary Key checkbox, and click OK.

The CMP Fields page shows the field you edited as the primary key.

Repeat Step 3 and Step 4 as needed for another field, if your bean needs a composite primary key.

In this page, you can't remove a field or add a new field, but you can edit an existing one.

5. Click Next.

The CMP Entity Bean Class Files page lists the elements of the CMP entity bean you are about to create.

If your bean needs to use another interface, use the Modify Interface button to specify it.

If your bean needs a different primary key class, either a new one or an existing one, use the Modify Class button to specify it.

6. When you are done, click Finish.

Your CMP entity bean's infrastructure is generated automatically by the EJB Builder. See Looking at a CMP Entity Bean's Classes for more discussion.

Using a CMP 1.x Bean Class

You might want to base your new CMP entity bean on an existing CMP entity bean that was created in the EJB 1.0 environment. If you choose this option, your bean will be a version 2.0 Enterprise JavaBean with a CMP version of 1.x, and the bean will not support EJB 2.0 features like local and local home interfaces.

In the wizard's CMP Entity Bean Name and Properties page, you select CMP 1.x Bean Class. (Notice that, when you've made this selection, only remote interfaces are available.) Click Next. The wizard then presents a navigation list from which you pick a bean class.

You should now be in the Select a CMP 1.x Bean Class page. Do as follows:

1. Navigate to the bean class you want to use, and select the class.

Notice that the IDE presents only the bean class for selection, not the other elements of the bean. When you have selected the class, the Next and Finish buttons are enabled.

2. Click Next.

The IDE presents the fields of the bean class you selected. Even if the original CMP entity bean had a primary key, in this page you must designate one or more fields as the primary key.

3. Select the field that should be the primary key and click Edit.

The Edit Persistent Field dialog box appears.

4. Make any necessary changes, including checking the Primary Key checkbox, and click OK.

The CMP Fields page shows the field you edited as the primary key.

Repeat Step 3 and Step 4 as needed for another field, if your bean needs a composite primary key.

In this page, you can't remove a field or add a new field, but you can edit an existing one.

5. Click Next.

The CMP Entity Bean Class Files page lists the elements of the CMP entity bean you are about to create.

If your bean needs to use another interface, use the Modify Interface button to specify it.

If your bean needs a different primary key class, either a new one or an existing one, use the Modify Class button to specify it.

6. When you are done, click Finish.

Your CMP entity bean's infrastructure is generated automatically by the EJB Builder. See Looking at a CMP Entity Bean's Classes for more discussion.

Creating Your Bean's Persistent Fields From Scratch

In the EJB Builder's Entity EJB Type page, you might have selected Create From Scratch because your database hasn't yet been created, you don't yet have access to it, or you don't know its location. Or, you might want the application server to create the database when the application that contains the enterprise bean is deployed.

Your CMP entity bean's container might require that your bean be mapped to a database, but not until the assembly and deployment stage. When you select the Create From Scratch option, the fields you specify are marked as persistent in the deployment descriptor, which is later used to notify the container which fields it should map into the database schema. This mapping is done just before the J2EE application is deployed.

The IDE gives you the option of setting up your entity bean's connection by stating your bean's Java field names. Later, during preparation for deployment, you can specify the rest of the database connection information.

In the wizard's CMP Entity Bean Name and Properties page, do as follows:

1. In the EJB Name field, type a name for your bean.

2. If you want your bean to reside in a different location than shown, use the Browse button to select an existing Java package.

3. Select Create From Scratch and click Next.

The CMP Fields page appears. The wizard has automatically supplied your bean one default CMP field named defaultField.

4. If you want to name your CMP fields at this time, select the default field and click Edit.

Name and define your field, following these guidelines:

5. Click Add to define each additional persistent field individually.

6. Click Next to examine or change the default classes that the wizard assigns. (Or, click Finish to skip this step and have the wizard generate your bean's infrastructure.)

The wizard's CMP Entity Bean Class Files page appears, listing the parts of your entity bean's infrastructure: the bean class, the interfaces you chose (local, remote, or both), and the type of the primary-key class.

In this page, you can accept or change your bean's classes. The wizard lets you specify another bean class, interface, or primary-key class if you wish. As you see if you click one of the Modify buttons, you can specify another package for the class or interface to reside in or to come from.

However, first you should find out whether the application server you plan to use supports this distribution of files.

7. Click Finish.

Your CMP entity bean's infrastructure is generated automatically by the EJB Builder Wizard. Now let's look at the generated classes.


Looking at a CMP Entity Bean's Classes

The EJB Builder wizard generates the default CMP entity bean classes for you and sets up the relationships between all the classes. FIGURE 4-2 shows how a typical CMP entity bean appears in the Explorer's Filesystems page. In this example, the default, Local Interface Only, is in effect. This bean is called only by other application components running in the same JVM.

 FIGURE 4-2 Default Classes of a Typical CMP Entity Bean

Screenshot showing the classes generated for a typical CMP entity bean with local-type interfaces.[ D ]

Of the four nodes shown in FIGURE 4-2, three represent actual classes (marked with class icons) and one is a logical node (marked with a bean icon). Do all your editing in the logical node. The example bean's primary nodes are described next.

If you created a primary-key class (for example, if your bean has a composite primary key), the Explorer shows an additional node for your bean.

Screenshot showing the classes generated for a CMP entity bean that has a primary key class in addition to a bean class and local-type interfaces. 

If you chose Both Remote and Local Interfaces (if your bean might be used both by beans in their own application's JVM and by beans in another JVM), the resulting CMP entity bean has all four interfaces.

Screenshot showing the classes generated for a CMP entity bean that has both local-type and remote-type interfaces. 

Expanding the Nodes

When you expand the nodes under your entity bean's package node, you see something like the tree view in FIGURE 4-3. (In this case, the default, Local Interface Only, has been used.)

 FIGURE 4-3 Explorer's Detailed View of a Typical CMP Entity Bean With Local Interfaces

Screenshot showing expanded tree view of the Java package BankData and the nodes of the CMP entity bean it contains.[ D ]

If you generated a new primary-key class, it appears in the Explorer as shown in FIGURE 4-4.

 FIGURE 4-4 Explorer's Detailed View of a Typical CMP Entity Bean With a Composite Primary Key

Screenshot showing the classes generated for another example CMP entity bean that has a primary key class. [ D ]

Reviewing the Generated Classes

Any fields that were mapped from database columns appear in your CMP entity bean. In addition, certain default methods are automatically placed in all entity beans.

Default Finder Method

Because the Enterprise JavaBeans Specification requires every entity bean to be locatable by its primary key, the method signature findByPrimaryKey is added automatically to your entity bean's home interface. In a CMP entity bean, the method signature is enough because your bean's container will implement the findByPrimaryKey method.

public CustomerLocal findByPrimaryKey(java.lang.Integer aKey)
	throws javax.ejb.FinderException;

Persistent Fields and Accessor Methods

The IDE generates and places in the bean class a get method and a set method for every persistent field that you specified for your CMP entity bean. To see these accessor methods, right-click the logical node and choose Open. The Source Editor opens to display the generated bean class source code. Near the end of the code, you see something like the following example:

public abstract java.lang.Integer getCustomerNum();
public abstract void setCustomerNum(java.lang.Integer 
	customerNum);
public abstract java.lang.String getDiscountCode();
public abstract void setDiscountCode(java.lang.String 
	discountCode);
public abstract java.lang.String getName();
public abstract void setName(java.lang.String name);

The CMP fields themselves are declared in the deployment descriptor. To see them, select the logical node's bean class, right-click, and choose View Deployment Descriptor. Here is a partial example of a deployment descriptor's XML code that declares the CMP fields customerNum, discountCode, and name for a CMP entity bean whose persistence plan, or abstract schema, is known by the name Customer:

<abstract-schema-name>Customer</abstract-schema-name>
<cmp-field>
	<field-name>customerNum</field-name>
</cmp-field>
<cmp-field>
	<field-name>discountCode</field-name>
</cmp-field>
<cmp-field>
	<field-name>name</field-name>
</cmp-field>
... 
<primkey-field>customerNum</primkey-field>

If you have not specified any persistent fields, your CMP entity bean contains one CMP field, called defaultField, and the accessor methods on that field. This field is automatically made the primary key.

After you use the wizard to define the CMP entity bean, you can always add CMP fields. Add a field by selecting the bean's logical node, right-clicking, and choosing Add CMP Field. You can also designate a new CMP field as a primary key.

After creating your bean, you can still change the name of a CMP field. Make the change only by selecting the CMP field under the logical node, right-clicking, and choosing Rename. The EJB Builder prompts you for the extent of the change.

The rest of your CMP entity bean's persistence (the actual SQL statements your bean needs for assembly and deployment within the server) is handled later. You make your bean portable across application and database servers by adding select or finder methods with EJB QL statements. These EJB QL statements are kept in the deployment descriptor for the EJB container and application server that you select. During deployment, this EJB QL code is converted to server-specific database-access code. Since most persistence is implemented using relational databases, SQL is the usual target language. For more information, refer to your server's documentation or online help.

For details on preparing enterprise beans for deployment, see Chapter 8. For details on writing EJB QL code, see the IDE's online help.

Primary-Key Class and Required Methods

The EJB Builder wizard either mapped the database table's primary key to a primary-key field in your CMP entity bean or let you define one or more primary-key fields. If your bean had a composite primary key, the wizard generated a primary-key class. (If not, your bean doesn't contain a primary-key class. Later, when you need to create the primary-key field that maps to the database table's primary key, you must first create the primary-key class. See Creating a New Primary Key.)

The primary-key class contains the set of data needed to uniquely identify an instance of the bean. If the bean has a single primary-key field, the wizard uses the field's class as the bean's primary-key class. If the bean has a composite primary key (one made up of more than one persistent field), the wizard generates a primary-key class with fields of the same name and type.

In addition, if a new primary-key class was generated, the EJB Builder inserted two methods required for the container, as follows:

public boolean equals(java.lang.Object otherOb) { 
	...
} 
public int hashCode() { 
	...
} 

The equals method compares objects with the same id value, that is, keys that evaluate to the same hash code. Call this method with a key value as its parameter. The method must ascertain whether the passed key value matches the current key value.

The hashCode method converts a key to an integer value so that the key can be looked up quickly in a hash table. Make sure this method returns a hash-code key for the current instance. The value doesn't need to be unique, but your entity bean will have better performance when there is little chance of a duplicate hash value.

The primary-key class must implement the java.io.Serializable interface, not the java.rmi.Remote interface.

If you plan to use the IDE's testing feature to exercise your CMP entity bean's methods, here are a couple of tips:

  • Include either an all-fields constructor in the bean's primary-key class or set methods for the class members.
  • Define an appropriate toString method to make the test application's display easier to interpret.

For more information on using the testing feature, see Chapter 9.

A CMP Entity Bean's Life-Cycle Methods

The wizard adds the following default life-cycle methods to the bean class of any entity bean:

public void setEntityContext(javax.ejb.EntityContext aContext) { 
	context=aContext;
}
public void unsetEntityContext() {
	context=null;
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbLoad() {
}
public void ejbStore() {
}
public void ejbRemove() {
}

Table 4-2 describes the purposes of these methods in a CMP entity bean.

TABLE 4-2 Purpose of Default Life-Cycle Methods in a CMP 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 nonpersistent field named context.

unsetEntityContext

This method lets you deallocate resources and release memory used by the entity bean instance, before the container destroys the instance. By default, the EJB Builder wizard sets the value of the context field to null.

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.

ejbLoad

In a CMP entity bean, this method needs no further coding. The container calls ejbLoad on a bean instance in the ready state and synchronizes the bean instance's state with the state of the entity in the underlying database.

ejbStore

In a CMP entity bean, this method needs no further coding. The container calls ejbStore on a bean instance in the ready state. The container synchronizes the state of the entity in the underlying database with the bean's state.

ejbRemove

In a CMP entity bean, this method does some cleaning up to prepare for the container's data deletions.



Completing Your CMP Entity Bean

To complete your CMP entity bean, do the following:

  • Define a create method if you want to let the bean's client insert data into the database. An entity bean can have more than one create method.
  • If necessary, add or replace a primary key.
  • Define all business methods that your bean needs.
  • Define any finder methods that your bean needs in addition to findByPrimaryKey.
  • Define one or more home methods if a bean needs to perform an operation that does not depend on any given bean instance.
  • Define one or more select methods, if you want your CMP entity bean to query other beans within the same EJB module or to query the database and return a local or remote interface.
  • Add code, if necessary, to complete your CMP entity bean's setEntityContext, unsetEntityContext, ejbActivate, ejbPassivate, and ejbRemove methods.

You might need to add one or more CMP fields if, while using the wizard, you didn't specify all the fields that your bean needs.

Make the basic parts of your additions in the Explorer by using the GUI tools that the IDE provides under the logical bean node. You provide the content of these methods as follows:

1. Name the method and completely define the method signature within the appropriate dialog box. Select the logical node, right-click, and choose Add Create Method, Add Business Method, Add Finder Method, Add Home Method, or Add Select Method. The EJB Builder propagates your method to the right classes of the CMP entity bean.

2. Finish coding the method body within the Source Editor.

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.

Defining Create Methods

Your entity bean can have more than one create method. In each bean, the home interface must have a create method, and the bean class must have corresponding ejbCreateXxx and ejbPostCreateXxx methods. When you use the recommended process, the IDE ensures that these methods are generated and propagated correctly.

In a CMP entity bean, the ejbCreateXxx method typically does the following:

  • Validates client-supplied arguments.
  • Initializes the instance's variables (in a CMP entity bean, the CMP fields). The container calls ejbCreate just before writing the bean's CMP fields to the database.

The ejbPostCreateXxx 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 the method 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 ejbPostCreateXxx method.

Define a new create method as follows:

1. Select the CMP entity bean's logical node, right-click, and choose Add Create Method.

The Add New Create Method dialog box appears.

2. Name your create method, using (if you like) an 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 type and name.

In a CMP entity bean, the create method must return a primary-key type or the same type as the primary key. As shown in the code example that follows, the method signature in the bean class specifies the primary-key type. However, the method body should return null, because the container manages the primary key of a CMP entity bean.

public PrimaryKeyType ejbCreate(param1...) throws exc1 

5. Click OK.

The method you added now appears in the bean class code as ejbCreateXxx and in the home interface as create. The method ejbPostCreateXxx also appears in the bean class. If you happen to have the Source Editor open while you are adding the method, notice that the code is immediately updated.

An example follows of ejbCreate and ejbPostCreate methods generated in the bean class:

public String ejbCreate(java.lang.String custname) 
	throws CreateException { 
} 
public void ejbPostCreate(java.lang.String custname) 
	throws CreateException { 
} 

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

The create method in CODE EXAMPLE 4-1 is designed for a web application that lets a bank's staff look up customer responses to a survey on service quality in the bank's branch offices. In the code example, an instance of a CMP entity bean is created with the fields custname, branchno, and response.

CODE EXAMPLE 4-1 Example of a Create Method in a CMP Entity Bean Class
public CustomerSurveyKey ejbCreateResponse(java.lang.String custName, 
	java.lang.String branchNo,java.lang.String response) 
	throws CreateException {
			if ((branchNo == null) || (custName == null)){
				throw new CreateException("Both the branch number and 
						the customer name are required.");
			} 
			setCustName(custName);
			setBranchNo(branchNo);
			setResponse(response);
 
			return null;
} 

Adding or Replacing a Primary Key

If you have deleted your entity bean's primary-key class or if you need to add a primary key to the class, use the property sheet as follows:

1. Select the logical node, right-click, and choose Properties.

The property sheet for your entity bean appears.

2. Select the Primary-Key Class field. Click the ellipsis (...) button.

The Property Editor dialog box appears.

3. Select an existing field or a class you have defined. Click OK.

The Primary-Key Class field now displays the return type of the new field or class.

Creating a New Primary Key

If you need to add a new primary key to an entity bean that has no primary-key class, you must first add the new primary-key field or fields to the bean. Then, you use the EJB Builder wizard to create a new entity bean with a primary-key class, for temporary use. (We'll call this the temporary bean.) Finally, you specify that the original bean is to use the new primary-key class.

Follow these steps:

1. In the Explorer, find the package of the entity bean that needs a primary-key class.

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

3. Expand the J2EE node, select CMP Entity EJB, and click Next.

4. In the wizard, do the following:

a. Specify only the field or fields that your existing entity bean needs for its primary key.

b. In the next-to-last panel, if you like, you can rename the primary-key class to correspond to the original bean that will be using the class.

For example, if your bean is named Account, you might rename the class AccountKey.

5. Click Finish.

Your temporary bean has now been created. Continue as follows:

6. In the Explorer window, if you like, you can delete the temporary bean's classes and logical nodes except for the primary-key class.

7. Right-click the original bean's logical node and choose Properties.

8. In the property sheet's Properties tab, click the Primary Key Class field and then the ellipsis (...) button.

The Primary Key Class dialog box opens.

9. Click this option: Select an existing user-defined class.

A file chooser opens.

10. Navigate to the new primary-key class, select it, and click OK.

In the property sheet, the Primary Key Class field changes to show the name of the new primary-key class.

A warning or error badge might appear on your bean's logical node. Disregard it for the moment. Dismiss the property sheet when you are done.

11. Right-click the original bean's logical node and choose Validate EJB or Error Information.

The IDE points out any errors you must resolve.

12. Fix all errors and revalidate or compile your bean.

The two methods required by the primary-key class, equals and hashcode, are not regenerated during this process. Typically, therefore, you must change the class names in the equals method. You might need to specify a different parameter type in the findByPrimaryKey method and a different return type for any ejbCreate methods in the bean class.

13. Save your work.

Handling Foreign Keys

If you need to maintain a relationship between CMP entity beans that is implemented as a foreign key, or if your bean needs multiple access to the data store, you should consider creating a set of related CMP entity beans instead of creating the beans separately. The EJB Builder wizard lets you create an entire related set at once, with the source tables' foreign keys intact and represented as container-managed relationships (CMRs) between beans. See Chapter 5 for details.

Defining Business Methods

You add a business method to your CMP entity bean to perform the business logic that needs to be encapsulated within the entity bean. Usually, a business method manipulates one or more persistent fields, but it doesn't access the database directly. The task of the business method is to update the instance variables. The methods ejbLoad and ejbStore are called by the EJB container as required by the semantics of the transaction, and the variables are thus written to the database.



Note - It is best to keep business logic separate from database access code.



Define a business method as follows:

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

The Add New Business Method dialog box appears.

2. Type a name for the method, and specify a return type, parameters, and exceptions. Click OK to dismiss the dialog box.

3. Finish the method's coding in the Source Editor.

Or, in the Add New Business Method dialog box, you can simply type a name for your new business method, click OK to dismiss the dialog box, and finish the coding in the Source Editor.

The business method in CODE EXAMPLE 4-2 is designed for the same application mentioned in CODE EXAMPLE 4-1. In this example, the bank customer's phoned-in comments are retrieved from the database.

CODE EXAMPLE 4-2 Example of a Business Method in a CMP Entity Bean
public java.lang.String retrieveComments() { 
	return phoneResponse(); 
} 

To see any method you have created for an enterprise bean, expand the bean's logical node and navigate to the sub-node for the kind of method you want to view. Right-click the method's node and choose Open. The Source Editor opens the class directly to the method code.

Adding Finder Methods

The EJB Builder wizard generates a default findByPrimaryKey method for you. However, if you want your CMP entity bean to run additional queries, you must define additional finder methods.

Alternatively, if you want a query to return the value of a related entity bean's persistent field, or if you don't need the method to be invocable by a client, you can use a select method. See Defining Select Methods for more information.

Add a finder method as follows.

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

The Add New Finder Method dialog box appears.

2. Type a name for the method, starting with find.

3. Select one of the following return types:

  • A single object, which is shown with a default name
  • A collection
  • An enumeration

4. Specify parameters and exceptions.

5. Type EJB QL statements into the Select, From, and Where fields.

For detailed EJB QL syntax and examples, see the IDE's online help. Also see Understanding the Application Server's Generated SQL if you're working with a CMP entity bean of an earlier version.

If you're not ready to input EJB QL statements at this point in the process, you can turn off the compiler's requirement for EJB QL code. See Compiling and Validating Enterprise Beans. However, you must supply the correct EJB QL statements before you deploy the bean to the application server.

A method's EJB QL code goes into the deployment descriptor. You can edit or add EJB QL statements using the Customizer or the method's property sheets. However, normally, you shouldn't edit the bean's deployment descriptor directly.

6. Click OK when you are finished.

Open the Source Editor directly to a finder method as follows: Go to the CMP entity bean's logical node and navigate to Finder Methods. Select the finder method you want, right-click, and choose Open. In the Source Editor, the home interface class opens to the finder method. (Finder methods are not declared in the bean class.)

Here are two tasks a finder method in the Account example might do:

  • Find an AccountEJB instance that holds data for a specific account and returns a remote object for that instance. For that purpose, you select the account by account number.
  • Find an AccountEJB instance for every overdrawn account and return a collection of their remote objects. For that purpose, you select for accounts with negative balances.

You can edit the finder method either using the Customizer (right-click the method's node and choose Customize) or using the method's property sheet (right-click the method's node and choose Properties).

Defining Home Methods

You can use a home method to perform an operation that does not depend on any given instance of the entity bean. A home method, similar to a static method, contains business logic that applies to all beans of a given class. (A business method, on the other hand, has an identity and logic unique to one instance of the entity bean.) A home method does not access the bean's persistence state (instance variables) or container-managed relationships.

For example, assume that your CMP entity bean Invoices reflects customer invoices, and each invoice shows the amount the customer has paid. If you want to see the total of all outstanding invoices, you can add a home method called getAmountDue that iterates through the collection of bean instances and invokes a business method to sum the balance due for all active invoices.

Define a home method as follows:

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

The Add New Home Method dialog box appears.

2. Type a name for the method.

3. Specify the return type, parameters, and exceptions.

4. Click OK when you are finished.

Alternatively, you can simply type a name for your new home method, click OK, and finish the coding in the Source Editor.

If the CMP entity bean has two client views (both kinds of interfaces), the EJB Builder asks you whether to include the home method on the local home interface, the (remote) home interface, or both.

The IDE adds the home method to the home interface or interfaces, and it adds the corresponding ejbHome method to the bean class.

Defining Select Methods

You can add one or more select methods if you want your CMP entity bean to query the database and return a local or remote interface (or a collection of interfaces), or if you want the method to return the value of a related entity bean's persistent field (or a collection of those values). A select method is related directly to the get method that is created when a relationship between CMP entity beans is defined, and the select method can be invoked only by a method (usually a business method) within the entity bean class. A select method is not exposed in any remote-type interface, and so it can't be invoked by a client.

Add a select method as follows:

1. Select the bean's logical node, right-click, and select Add Select Method.

2. Type a name for the method starting with ejbSelect.

3. Select one of the following return types:

  • A single object, which is shown with a default name
  • Any other type on the combination box list

4. Specify parameters and exceptions.

5. Type EJB QL statements into the Select, From, and Where fields.

For detailed EJB QL syntax and examples, see the IDE's online help.

6. Click OK when you're finished.

You can edit the select method either using the Customizer (right-click the method's node and choose Customize) or using the method's property sheet (right-click the method's node and choose Properties).

The EJB QL code that you supply goes into the deployment descriptor. You can edit or add EJB QL statements using the Customizer or the method's property sheets. However, you can't edit the bean's deployment descriptor directly.

Defining Private Methods

If you want to make sure a business method can't be overridden by a subclass, you can define the method as private. This ensures that the method is treated as final. To create a private business method, do as follows:

1. Expand the entity bean's logical node.

2. Right-click the Bean Class node and choose Add right arrow Method.

The Add New Method dialog box appears.

Notice that this dialog box lets you define the method's level of access (public, private, or protected) and select other modifiers (abstract, static, transient, native, final, synchronized, and volatile).

As with other business methods, you can use this dialog box to define parameters and exceptions, or you can finish all the method's code in the Source Editor.

Defining Additional Fields

After creating your CMP entity bean, you can add CMP fields as follows:

single-step bulletSelect the logical node, right-click, and choose Add CMP Field.



Note - Don't use the Source Editor to code the field directly in your bean class. The IDE has no way to identify the field as persistent in the deployment descriptor.




After Creating Your CMP Entity Bean

Your CMP entity bean is now finished except for a few steps that 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 the following documents: