Home > Articles > Programming > Java

Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020