- EJB and JDBC
- Entity Bean Server Components
- Entity Bean Client Interfaces
- Entity Bean Configuration and Deployment
- Conclusions
Entity Bean Server Components
An entity bean is a class that represents a logical classification of data in a database. An entity bean class contains fields that map to elements of a database schema definition. Entity bean fields most easily map directly to columns of a database table, and the entity bean itself might be likened to an actual database table. Relations among entity beans thus are analogous to relations among tables. Views and table joins also might be likened to an entity bean, with the elements of those data sources mapping to the fields of an entity bean class.
Entity bean instances that contain populated values within their fields correspond to an actual entry within a data source. Thus, an entity bean instance corresponds to a particular row within a table or perhaps might be related to the single result of a table join query.
Entity bean components can be developed in one of two ways by developers. Bean-managed persistence (BMP) entity beans contain code (typically JDBC code) created by developers to manage all database inserts, deletions, queries, and updates associated with a particular entity bean. Container-managed persistence (CMP) entity beans are defined so that the EJB containers can automatically provide all the code required for managing all database inserts, deletions, queries, and updates associated with the entity bean. Developers opt to use BMP entity beans most often when their container does not support CMP entity beans, when a particular data source is too complex to enable effective CMP entity bean mapping, or when the developer desires more controllability over how the data should be managed. Otherwise, CMP entity beans can significantly reduce the amount of hand-coding required to data enable enterprise applications. This article describes the concepts involved with entity beans in general and also describes the specific approaches to building both BMP and CMP entity bean components.
Primary Keys
Although EJB containers may pool entity beans and reuse server-side entity bean instances to encapsulate different data-source entries at different times, there must be a way to uniquely identify a particular data-source entry. If the client-side handle were to simply refer to the server-side entity bean instance directly, there would be no guarantee that the instance is actually related to the correct data-source entry, given the EJB container instance pooling and reuse policies.
Entity beans thus utilize the concept of a primary key. A primary key uniquely identifies the data-source entry that is associated with a particular entity bean instance. That is, although a particular entity bean instance can be allocated with different data-source entry values at different times by a container, the primary key provides a way to identify the particular data-source entry that should underlie an entity bean instance. When EJB clients create or look up particular data-source entries using entity bean interfaces, the container associates a primary key with the EJB entity bean handle(s) returned to the client. For example, if a customer entity bean has a customer first and last name that represents a primary key for a customer entity bean, those two values should uniquely identify a row in a customer table for the container. From the programmer's point of view, however, it maps to a unique entity bean instance.
Bean-Managed Persistence Entity Beans
Many of the concepts and techniques used to build BMP entity beans also apply to CMP entity beans. However, as you will see, BMP entity beans require a significant amount of hand-coding. In a certain sense, there is not much difference between using BMP entity beans and creating home-grown JDBC-based components. The difference lies in how the implementation of such JDBC logic is encapsulated. Specifically, standard methods on a BMP entity bean imply which JDBC statement types should be created and processed.
BMP Entity Bean Logical Component Architecture
Figure 1 introduces the basic elements needed to construct a BMP entity bean.
Figure 1 Bean-managed persistence entity EJBs.
Public, nonfinal, and nonabstract entity bean implementations, such as MyBeanManagedEntityEJBean, must implement the javax.ejb.EntityBean interface, which extends the EnterpriseBean marker interface. The EntityBean interface defines a set of operations that must be implemented by an entity bean to support the life-cycle management contract required by the EJB container. Bean-managed entity EJBs can also implement business-specific methods, such as the someMethod() and anotherMethod() sample methods shown in the figure. A bean-managed entity bean also typically defines some state in the form of field variables that contain cached versions of the data-source entry values. As a final note, entity bean implementations must also have a public parameterless constructor and should not implement the finalize() method.
BMP Entity Bean Interfaces
The javax.ejb.EntityContext interface is implemented by a container object that provides a handle to an entity bean's runtime context. EntityContext extends the more generic EJBContext and defines a method for obtaining a handle to a remote EJB interface handle, as well as for obtaining a handle to the bean instance's primary key. The setEntityContext() method on an EntityBean implementation is invoked by a container immediately after an instance of the bean is constructed. The bean should save this value in a field variable for later use. An unsetEntityContext() method is also required to be implemented by entity bean implementations. A container calls this method when the entity bean instance is to be decoupled from the container context.
Whenever a client wants to locate particular existing entity bean instances that correspond to particular existing data-source entries, the container invokes one of the ejbFindXXX(...) methods on the entity bean. The ejbFindXXX(...) methods fulfill a role similar to that of a SQL SELECT statement in database functionality. BMP implementations generally need to throw a FinderException when processing these methods to indicate that an application error has occurred.
The ejbFindByPrimaryKey() method must be defined on all entity beans. An implementation of this method must take the primary key of an entity bean as an input parameter, verify that the associated data-source entry identified by the primary key exists in the database, and then return the primary key to the container. If the requested data-source entry does not exist, a BMP implementation may throw the ObjectNotFoundException subclass of FinderException to indicate that the requested object could not be found. Most likely, a BMP entity bean will formulate a SELECT statement query to issue to the database via JDBC to implement this method, to verify that the data with the primary key exists in the database.
Zero or more additional ejbFindXXX(...) methods may also be defined that take zero or more business-specific input parameters and that must attempt to locate any associated data-source entries in the database. For each located entry, a collection of primary keys associated with each entry should be returned from the ejbFindXXX() method. A BMP implementation of these methods can utilize the JDBC API to issue a SQL SELECT statement as a function of the input parameters and bean type. Then it can use the results to create a collection of associated primary key objects. If the underlying query results in no primary keys to return, an empty collection should be returned.
Zero or more ejbCreate(...) methods with zero or more parameters may be defined on an entity bean. The optional ejbCreate() methods perform a function akin to database INSERT statements: They create an entry in the data source associated with this entity bean type and then populate it with any data established within the entity bean. Data can be established within the bean via the initialization of any field variables during construction, and any values passed as parameters to an ejbCreate(...) method can be used. A container calls ejbCreate(...) on an entity bean as a result of a client-induced creation event on the bean. The ejbCreate(...) methods must return an application-specific Java Object that represents the primary key for this newly created entity bean.
BMP entity beans must implement the necessary database connectivity logic to perform the database SQL INSERT within the ejbCreate(...) methods. The primary mechanism to accomplish this task is the JDBC API, which can be configured via XML-based data-source configuration parameters. BMP entity beans may throw the CreateException to indicate that an entity bean cannot be created for some reason. BMP entity beans may also throw the DuplicateKeyException subclass of CreateException if an entity bean could not be created because a data-source entry with the same primary key exists.
For each ejbCreate(...) method defined, the entity bean must also define an ejbPostCreate(...) method using the same input parameters. The ejbPostCreate() method is called by the container after it calls ejbCreate() and after the container associates an instance of the entity bean with the client reference. Thus, any initial actions that your entity bean wants to perform using a fully associated entity bean instance can be done when this method is called. The ejbPostCreate(...) methods may also throw a CreateException to indicate an application error that has occurred during this method call.
When a client induces a remove action on an entity bean, the container calls the ejbRemove() method. The ejbRemove() method for an entity bean means that the associated data-source entry should be deleted from the database akin to a SQL DELETE statement in functionality. A BMP entity bean will need to obtain a handle to the primary key using its entity context's getPrimaryKey() method and then use the JDBC API to formulate a SQL DELETE statement for this particular data-source entry. A BMP implementation of ejbRemove() may also throw the RemoveException to indicate a general exception that occurred during the attempted deletion operation.
The ejbPassivate() and ejbActivate() methods must be implemented for entity beans as they were for stateful session beans. The ejbPassivate() method is called by the container before it returns the entity bean to the pool of bean instances. The ejbActivate() method generally performs the inverse operations of ejbPassivate(). A container calls ejbActivate() when it needs to bring the state of a previously passivated bean into active memory due to some client demand on that bean.
Whereas ejbPassivate() and ejbActivate() relate to closing and opening any resources not related to the data source, the ejbLoad() and ejbStore() methods explicitly deal with the data-source information. A container calls ejbStore() and ejbLoad() on an entity bean whenever it wants the bean to synchronize the state of the database field data in the bean with the state of the associated data actually stored in the data source.
A container calls ejbStore() on a bean when it wants the bean instance to update the associated data-source entry with the state of the data in the bean instance. This operation thus satisfies a function similar to that of a SQL UPDATE in the database. BMP implementations typically use JDBC to implement SQL UPDATE statements when ejbStore() is invoked.
A container calls ejbLoad() on a bean when it wants the bean instance to be updated with the latest state values of the associated data-source entry in the database. This operation thus updates the in-memory bean instance representation of the database entry. A BMP implementation typically calls getPrimaryKey() on the associated entity context to first determine the specific data-source entry associated with this bean instance. The BMP implementation then queries the data-source entry's element values using JDBC and updates the state of the bean.
Container-Managed Persistence Entity Beans
As you have just seen, creating BMP entity beans can be quite a chore. Although the amount of hand-coding might be equivalent to what you would expect for implementing JDBC-based connectivity to access your enterprise data, EJB also provides a means to simplify the amount of effort required to create entity beans via its container-managed persistence (CMP) entity bean standards. With CMP, the container implements all the JDBC database access logic for you. The container thus handles the object-to-relational mapping necessary to transfer data from your EJB entity object to relational database entities and from the relational database entities to your EJB entity object.
In the following sections, I primarily focus on aspects of developing CMPs that differ from the development of BMPs and avoid reiterating discussion of the common concepts shared by CMPs and BMPs.
CMP Entity Bean Logical Component Architecture
Figure 2 depicts the basic architecture behind creating CMP entity bean components. A public, nonfinal, and nonabstract CMP entity bean implementation, such as MyContainerManagedEJBean, must implement the EntityBean interface. CMP entity EJBs can also implement business-specific methods, such as the someMethod() and anotherMethod() sample methods shown in the figure. Also note that entity bean implementations must also have a public parameterless constructor and should not implement the finalize() method.
Figure 2 Container-managed persistence EJBs.
CMP Entity Bean Interfaces
CMP entity beans must take additional care to define any fields that will be managed by the container as public and to ensure that the associated types are serializable. These container-managed fields map directly to elements of the data-source entry associated with this CMP entity bean. For example, a container-managed field may map directly to a column in a particular database table. The container figures out which of the fields will be managed via a specification in the EJB deployment descriptor for this bean.
A primary key for a CMP entity bean may be specified simply as a single field of the CMP entity bean. CMP entity bean primary keys may also be uniquely defined using a separate class containing one or more public field names that map to field names of the CMP entity bean.
Setting and unsetting the EntityContext associated with a CMP entity bean is accomplished using the setEntityContext() and unsetEntityContext() methods, respectively. Containers call these methods on CMP entity beans for the same reasons and during the same phases of a bean's life cycle as they do for BMP entity beans.
CMP entity beans relieve the programmer from having to define and write ejbFindXXX(...) methods. Rather, the container deduces how to implement such methods for the CMP entity bean by reading certain configuration information from the EJB deployment descriptors. Implementation of these methods is thus transparent to the developer. These methods can be implemented by EJB vendor products within subclasses of the CMP entity bean or by separate entities to which the calls are delegated and the results are received. Regardless of the underlying implementation, the CMP bean developer need not worry about writing any code to support these operations.
The ejbCreate(...) methods are also optional for CMP entity beans. Thus, the bean developer need not worry about implementing the actual database INSERT-related code to support this method. The developer needs only to ensure that each container-managed field value is properly initialized with any default values and with values passed in as parameters to the ejbCreate(...) method. CMP bean providers must also define ejbPostCreate(...) methods that match ejbCreate(...) methods in terms of parameters.
The container calls ejbRemove() on a CMP right before it deletes associated data from the database. The bean developer needs only to focus on any actions that must be performed before the data is deleted from the database. The container implements all database deletion code and throws any EJB exceptions as appropriate.
The ejbPassivate() and ejbActivate() methods must be implemented by CMP entity bean developers, as they were for BMP entity bean developers. Developers must thus clean up any resources not related to the data-source within an ejbPassivate() method implementation. Developers must also reestablish any of those resources within an ejbActivate() method implementation.
The container for CMP entity beans also handles most of the work that was previously implemented inside ejbLoad() and ejbStore() BMP entity bean method calls. Containers manage the actual storage of data that was previously implemented within the ejbStore() call. CMP bean developers need to worry only about readying any container-managed field values for persistence to the database, such as deriving any recent updates that must be reflected in the container-managed field values before they are persisted. Similarly, CMP developers need to worry only about reflecting any changes that were made to a bean's field values within the ejbLoad() method implementation. After a container handles updating the container-managed field values, the ejbLoad() method is called and the CMP entity bean implementation of this method might need to derive any changes to other states that result from this synchronization with the database.