Home > Articles > Programming > Java

Entity EJBs: Implementation, Specification, and Deployment

In this sample chapter, Dan Haywood discusses how to implement Entity beans effectively, as well as EJB specification and deployment.
This sample chapter is excerpted from Sams Teach Yourself J2EE in 21 Days, by Dan Haywood.
This chapter is from the book

This chapter is from the book

Yesterday, you learned about Session beans, and how they provide a service to a specific client. Today you will learn

The major topics that you will be covering today are

  • How Entity beans represent domain objects, providing services that can be used by all clients

  • Two types of Entity beans—bean-managed persistence (BMP) and container-managed persistence (CMP)

  • How EJBs can provide a local interface in addition to their remote interface

  • Specifying, implementing, configuring, and deploying BMP Entity beans

  • Configuring and deploying EJBs from the command line rather than using a GUI


When building IT systems, the functionality required of the application must be specified and the business objects within the domain must be identified. In "traditional" client/server systems, the application's functionality can be implemented in the front-end application or perhaps using database stored procedures, and the domain objects are usually tables within an RDBMS. In building an EJB-based system, the application's functionality corresponds to Session beans, and the domain objects correspond to Entity beans.

You learned yesterday that Session beans take on the responsibility of implementing the application's business functionality. There will still be a presentation layer to display the state of those Session beans, but its detail is unimportant in the larger scheme of things.

In the same way, Entity beans take on the responsibility of representing the domain data. There will still a persistent data store to manage the data, almost certainly an RDBMS, but the Entity beans abstract out and hide the detail of the persistence mechanism.

The N-tier Architecture Revisited

On the very first day, you were introduced to n-tier architectures, with the business logic residing in its own tier. With an EJB-based system, both Session and Entity beans are objects, so the business logic could be reside in either of them. In practice, the business logic will be split over both, but to make the correct decision, it is worthwhile analyzing what is meant by that phrase "business logic."

Business logic refers to the collection of rules, constraints, procedures and practices put in place by the business users to conduct their business. Some of the rules and constraints cannot be changed by the business, due to the domain in which the business is performed. For example, there could be legal constraints and obligations. The procedures and practices represent the (one particular) way in which business users have chosen to conduct business.

Rules and constraints generally apply across all applications. In other words, it doesn't matter what the business is trying to accomplish, they will still need to comply with such rules and constraints. This sort of business logic is best implemented through Entity beans, because Entity beans are domain objects that can be reused in many different applications.

In the business world, procedures and practices are usually the expression of some sort of application, so Session beans are the best vehicle to implement this type of business logic. Indeed, introducing computerized systems often changes these procedures and practices (hopefully for the better, sometimes for the worse) because computers make available new ways of accomplishing tasks.

  • Session beans should have the business logic of a specific application—in other words, application logic. The functionality provided should allow the user to accomplish some goal.

  • Entity beans represent domain objects and should have business logic that is applicable for all applications—in other words, domain logic. Usually, this logic will be expressed in terms of rules and constraints.

If there is any doubt as to where the functionality should be placed, it is safer to place it with the Session bean. It can always be moved later if it is found to be truly re-usable across applications.

Figure 6.1 shows a UML component diagram to illustrate that there are at least four logical layers in an EJB-based system. Normally, at least some of these layers will be on the same physical tier.

Figure 6.1 EJBs separate out business logic into application and domain logic.

Comparison with RDBMS Technology

It's natural to compare Entity beans with relational databases, because there is a significant overlap in the objectives of both technologies.

If you like to think in client/server terms, you could think of Session beans as being an extension of the "client", and Entity beans as being an extension of the "server". It's important to realize that many clients can share a given Entity bean instance at the same time, just as many database clients can read some row from a database table at the same time.

You can also think of Entity beans as a high-performance data cache. Most RDBMS' store data pages or blocks in a cache so that the most commonly used rows in tables can be read directly from memory rather than from disk. Although the EJB specification does not require it, many EJB containers adopt a strategy such that Entity beans are also cached, so the data that they represent can also be read directly from memory. The advantage of the Entity bean cache over an RDBMS' data cache is that the Entity beans already have semantic meaning and can be used directly. In contrast, data read from an RDBMS' data cache needs to be reconstituted in some way before it can be used.

Identifying Entities

At their simplest, Entity beans can correspond to nothing more complex than a row in a database; any data that might reasonably be expected to exist in a relational database table is a candidate. This makes examples of Entity beans easy to come by:

  • A Customer Entity bean would correspond to a row in a customer table keyed by customer_num. The list of contact phone numbers for that Customer (in a customer_phone_number detail table keyed on (customer_num, phone_num) would also be part of the Customer Entity bean.

  • An Invoice Entity bean might correspond to data in the order and order_detail tables.

  • An Employee Entity bean could be persisted in an employee table. The employee's salary history might also be part of the Entity bean.

Identifying entities can be made easier if a proper discipline is adopted with relational modeling of the database. Of course, many databases just evolve over time as developers add tables to support new requirements. Ideally, though, there should be a logical database model and a physical database model. The former is usually captured as an Entity relationship diagram (ERD) with entities, attributes, and relationships. Relational database theory defines a process called normalization and different normal forms that aim to eliminate data redundancy. It is this stage at which the normalization rules are applied, to get to third normal form (at least).


This isn't a book on relational database design, but here's a cute phrase that you can use to get you to third normal form: "every non-key attribute depends upon the key, the whole key, and nothing but the key (so help me Codd!)." If you are wondering who Codd is, that's Dr. Codd who in the early 1970s laid down the mathematical foundations for relational theory.

Converting a logical database model to a physical model is in many ways mechanical. Every entity becomes a table, every attribute becomes a column, and every relationship is expressed through a foreign key column in the "child" table.

These entities identified in logical data modeling are the very same concepts that should be expressed as Entity beans. Moreover, one of the key "deliverables" from performing relational analysis is the selection of the primary key—the attribute or attributes that uniquely identify an instance. Entity beans also require a primary key to be defined, and this is manifested either as an existing class (such as java.lang.String or java.lang.Integer) or a custom-written class for those cases where the key is composite. The name often given to such primary key classes is something like BeanPK, although it can be anything. You can think of the primary key as some object that identifies the bean.


The requirement of a primary key class to identify Entity beans has led to criticism —in particular, by vendors of object-oriented DBMS—that the technology is not particularly object-oriented. In an OODBMS, the object does not need a primary key identifier; it is identified simply by its reference.

Nevertheless, there are some differences between relational entities and Entity beans. Whereas relational modeling requires that the data is normalized, object modeling places no such constraints. Indeed, not even first normal form (where every attribute is scalar) needs to be honored. For example, a Customer Entity bean might have a vector attribute called phoneNumbers, with a corresponding accessor method getPhoneNumbers() that returns a java.util.List. In a physical data model, there would need to be a separate table to hold these phone numbers.

Even with a solid logical data model to guide you, selecting Entity beans is not necessarily straightforward. In particular, choosing the granularity of the entities can be problematic. With the customer example given earlier, the customer_phone table doesn't really seem significant enough to be an Entity. It's just the way in which vector attributes have to be modeled in relational databases. But what of the invoices? After all, invoices are sent to customers, and any given invoice relates only to the orders placed by a single customer. So perhaps invoices should be considered as just vector attributes of customers, with a getInvoices() accessor method? On the other hand, many modelers would argue that the concept of Invoice is significant enough in itself—with its own state, behavior, and lifecycle—to warrant being represented as its own Entity bean.

Specifying the interfaces should help you decide which is the correct approach. If the invoice entity really is significant, you will find that the customer's interface will be bloated with lots of invoice-related methods. At this point, you can tease the two entity objects apart.


If you read old text books on EJB design, you will find that the traditional (pre EJB 2.0) advice for Entity beans is that they should be coarse-grained—in other words, that data from several tables correspond to a single entity. This advice arose because of a combination of factors relating to pre EJB 2.0 Entity beans, one in particular being that Entity beans had to be remote (implement the java.rmi.Remote interface).

These factors are no longer true, so the advice is out of date. Fine-grained Entity beans are perfectly feasible for an EJB container that supports the EJB 2.0 specification.

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.


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.


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.


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.


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


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


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.


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.


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