Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

2.4 Enterprise JavaBeans

Enterprise JavaBeans are server-side components that encapsulate an application's business logic. An enterprise bean, for example, might calculate interest payments for a loan application or access a relational database for banking applications. A client that needs information calls business methods in the EJB, which may result in a remote invocation across a network.

EJBs have several benefits. First of all, they help bean developers write large applications with distributed components more easily. Recall that the EJB container provides system-level services to each bean deployed in a J2EE application server. This means bean developers do not have to handle complex issues such as transaction management, resource pooling, security, and multithreaded programming. Instead, they focus only on business logic in their bean methods.

EJBs also benefit clients in the presentation tier. Clients become thinner, since they implement only presentation logic and use EJBs for their business methods. EJBs are also portable components, which means you can build different enterprise applications with the same EJBs and run them on any J2EE application server.

There are three types of enterprise beans: session beans, entity beans, and message-driven beans. Let's give you a brief overview of each enterprise bean and discuss how they might be used in an enterprise application. We'll also discuss bean life cycles and how the EJB container manages each bean.

Session Beans

Session beans represent an interactive session with one or more clients. Session beans may maintain state, but only during the time a client interacts with the bean. This means session beans do not store their data in a database after a client terminates. Session beans, therefore, are not persistent.

Session beans come in two flavors: stateless and stateful. Let's discuss the characteristics of each session bean and suggest when they might be appropriate in an enterprise application.

Stateless Session Beans

The values of any object's instance variables (fields) define the state of an object. Usually, method calls change an object's state. A stateless session bean, however, does not keep track of client-specific data. In fact, no instance variable in a stateless session bean stores client-specific data. This unique property allows the EJB container to create a pool of instances, all from the same stateless session bean. Why is this important?

When a client invokes a method of a stateless session bean, the EJB container fetches an instance from the pool. Any instance will do, since the bean does not store any client-specific information. As soon as the method finishes executing, the instance is available for another client's request. This arrangement makes stateless session beans highly scalable for a large number of clients (a small number of instances can service many clients). It also means better performance. The EJB container does not have to move stateless session beans from memory to secondary storage to free up resources—it simply regains memory and other resources by destroying the instances.

All enterprise beans have different states that they go through during their lifetimes. The life cycle of a bean is managed by the EJB container. Figure 2–3 shows the life cycle for a stateless session bean.

Figure 1-3Figure 2—3 Stateless Session Bean Life Cycle

There are only two states in a stateless session bean: a Does Not Exist state and a Ready state. After the container creates an instance of a stateless session bean with Class.newInstance(), the container invokes the setSessionContext() and ejbCreate() methods in the bean. This makes the bean transition to the Ready state. The bean developer uses the setSessionContext() method to access the bean's context from the container. The container invokes the ejbCreate() method to initialize the bean and access resources. Once the bean is in the Ready state, a client may call its business methods. The container calls the bean's ejbRemove() method when it no longer requires a bean instance. This makes the bean return to the Does Not Exist state.

When should you use stateless session beans? Stateless session beans are appropriate when a task is not tied to a specific client. You could, for instance, use a stateless session bean to send an e-mail confirmation or calculate interest payments for loan applications. You could also use a stateless session bean to read data from a database. Such a bean would be useful for generating reports or viewing a collection of items.

Stateful Session Beans

In a stateful session bean, the instance variables store client-specific data. Each stateful session bean, therefore, stores the conversational state of one client that interacts with the bean. This conversational state is maintained by the bean while clients call its business methods. The conversational state is not saved when the client terminates the session.

The EJB container manages stateful session beans differently from stateless beans. Note that with stateful session beans, it's not possible for the container to create a pool of instances and share them among multiple clients. Since a stateful session bean stores client-specific data, the container creates a separate bean instance for each client. So that conversational state is not lost, the container saves and restores stateful session beans when moving them between memory and secondary storage. All this means that stateful session beans have more overhead associated with them and are not as scalable as stateless session beans.

The life cycle of a stateful session bean is also more involved, as Figure 2–4 shows. Stateful session beans have three states: a Does Not Exist state, a Ready state, and a Passive state. When a client calls create(), the EJB container instantiates the bean with Class.newInstance() and calls its setSessionContext() and ejbCreate() methods. This makes the bean transition to the Ready state where it can accept calls to its business methods. When the client terminates a session, the container calls the ejbRemove() method in the bean. The bean returns to the Does Not Exist state where it is marked for garbage collection.

Figure 1-4Figure 2—4 Stateful Session Bean Life Cycle

A stateful session bean transitions to the Passive state when the container passivates the bean; i.e., the container moves the bean from memory to secondary storage. The container calls the bean's ejbPassivate() method just before passivating a bean. If the bean is in the Passive state when a client calls one of its business methods, the container activates the bean. The container restores the bean in memory before calling the bean's ejbActivate() method. This makes the bean return to the Ready state.

When should you use stateful session beans? In general, any situation where a bean must remember client information between method invocations is a candidate for stateful session beans. A good example on the web is a virtual shopping cart in an online store. When clients log on to the system, a stateful session bean can maintain the items in the shopping cart. Each client has its own instance of a stateful session bean, which maintains a separate shopping cart for each client.

Note that with stateful session beans, client-specific information is stored in memory, not to a database. Therefore, you should use stateful session beans in situations where losing session data is not a problem when a client terminates a session. In our hypothetical online store, for instance, we discard the virtual shopping cart if a client decides not to buy the items. Saving the shopping cart contents comes under the application and use of entity beans, our next topic.

Entity Beans

Entity beans are in-memory business objects that correspond to data in persistent storage. An entity bean typically corresponds to a row in a relational database. The bean's instance variables represent data in the columns of the database table. The container must synchronize a bean's instance variables with the database. Entity beans differ from session beans in that instance variables are stored persistently. Entity beans also have primary keys for identification and may have relationships with other entity beans. Another key concept is that clients may share entity beans.

The EJB container locates an entity bean by its primary key. Primary keys are unique identifiers. Database software prevents you from inserting new data if the primary key is not unique. If multiple clients attempt to access the same data in an entity bean, the container handles the transaction for you. Through an entity bean's deployment descriptor, the developer specifies the transaction's attributes associated with entity bean methods. The container performs the necessary rollbacks if any step in the transaction fails. This is one of the most vital services that the container provides for entity bean developers. We provide an overview of transactions and entity beans. See "Transaction Overview" on page 246 in Chapter 6.

An entity bean life cycle has three states: Does Not Exist, Pooled, and Ready. Figure 2–5 shows the life cycle diagram.

Figure 1-5Figure 2—5 Entity Bean Life Cycle

To transition from the Does Not Exist state to the Pooled state, the container creates a bean instance with Class.newInstance() and calls the setEntityContext() method in the bean. This allows bean developers to access a bean's context from the argument passed to setEntityContext(). In the Pooled State, all entity bean instances are identical.

Note that there are two paths for an entity bean to transition from the Pooled state to the Ready state. The client can invoke the entity bean's create() method and consequently insert new data into the underlying database. The client can alternatively invoke one of the bean's "finder" methods. This performs a select query on the underlying database, synchronizing the bean's persistent fields from the data already in the database.

If a client wants to insert data into the database, the client calls the create() method with arguments representing the data values. This makes the container call ejbCreate() to initialize the bean before calling ejbPostCreate(). In the Ready state, clients may invoke business methods in the entity bean.

If, on the other hand, a client reads data from the database, the client calls the findByPrimaryKey() method or another finder method. This makes the container deliver an entity bean instance directly to the client if its state is Ready. If the requested bean is in the Pooled state, the container activates the bean and calls the bean's ejbActivate() method. This changes the bean's state to Ready.

There are also two paths from the Ready state to the Pooled state. If a client wants to remove data from the database, the client calls remove(). This makes the container call the bean's ejbRemove() method. If the container needs to reclaim resources used by an entity bean, it can passivate the bean. To passivate an entity bean, the container calls ejbPassivate(). Both calls change the bean's state from Ready to Pooled.

At the end of the life cycle, the container removes the bean instance from the pool and calls the bean's unsetEntityContext() method. This changes the bean's state from Pooled to Does Not Exist.

When should you use entity beans? An entity bean is appropriate for any situation where data must be maintained (created, updated, selected, deleted) in persistent storage. Entity beans should represent business data rather than perform a task-related function.

Entity beans have two types of persistence: Bean-Managed Persistence (BMP) and Container-Managed Persistence (CMP). Let's take a look at each persistence type as it relates to a database.

Bean-Managed Persistence (BMP)

Entity beans with bean-managed persistence contain code that accesses a database. The beans' code contains SQL calls to read and write to the database. BMP gives developers more control over how an entity bean interacts with a database.

An entity bean with BMP can implement SQL code targeted for a specific database platform or it can use a Data Access Object (DAO) to hide the details of a particular database. A DAO encapsulates database operations into helper classes for a specific database. DAOs make entity beans with BMP more portable, although the bean developer still has to manipulate database access with Java methods and classes. We present the DAO pattern for BMP entity beans in Chapter 6 (see"DAO Pattern Implementation" on page 215).

Container-Managed Persistence (CMP)

Entity beans with container-managed persistence do not contain code for database access. The container generates the necessary database calls for you. This approach makes CMP entity beans more portable than BMP entity beans with DAOs. With the deployment descriptor set to specific attributes for CMP behavior, entity bean developers are spared from having to write SQL code for database access.

Entity Relationships

Entity beans, regardless of whether they use BMP or CMP for database access, can have relationships with other entity beans according to an abstract persistence schema. An entity bean's abstract schema defines a bean's persistent fields and its relationships with other entity beans. The persistent fields of an entity bean are stored in a database.

A bean's relationship to another bean is stored as a relationship field. Relationship fields must also be stored in the database. With BMP, the developer decides how relationship fields are represented in the underlying database (using foreign keys allows data in one table to relate to data in another table). With CMP, the container constructs the appropriate cross-reference tables based on the abstract schema description the bean developer provides. Chapter 7 explores entity relationships with CMP.

Message-Driven Beans

Message-driven beans allow J2EE applications to receive messages asynchronously. This means a client's thread does not block while waiting for an EJB's business method to complete. Instead of calling a business method directly in a bean, clients send messages to a server that stores them and returns control to the client right away. The EJB container has a pool of message bean instances that it uses to process messages. When the message is received, the message bean can access a database or call an EJB business method. This arrangement allows the invocation of lengthy business methods without making the client wait for the method to complete its job.

Using JMS

Message beans use the Java Message Service (JMS) to handle messaging. Figure 2–6 shows the approach. Clients use a JMS server to store messages in a

Figure 1-6Figure 2—6 Message-Driven Bean, JMS, and EJB Container Architecture

ueue or topic destination. In JMS, a topic is used for a one-to-many broadcast and a queue for a one-to-one communication. When a message arrives, the container calls the onMessage() method in the message bean to process the message. Using the JMS server as an intermediary decouples the client from the message bean. This is a key point with message beans.

The container uses a bean instance from a pool of message beans. The container also handles all the details of registering a message bean as a listener for queue or topic messages.

Another key point with message beans is that they are stateless. This makes message beans highly scalable, like stateless session beans. A message bean retains no conversational state and can handle messages from multiple clients. Message beans can connect to databases and call methods in other EJBs, too. This makes message beans a valuable component in enterprise designs that require asynchronous processing from clients.

Message beans also have a simple life cycle, as shown in Figure 2–7. There are only two states: Does Not Exist and Ready. To change from the Does Not Exist state to the Ready state, the container instantiates the message bean with Class.newInstance() and calls its setMessageDrivenContext() and ejbCreate() methods.

Figure 1-7Figure 2—7 Message Bean Life Cycle

In the Ready state, a message bean may receive messages from the JMS server. When a message arrives, the container calls the onMessage() method in the message bean and passes the message to the method as an argument. Note that message processing does not make a message bean change state.

Like stateless session beans, the container never passivates a message bean because message beans do not contain client-specific data. The life cycle of a message bean ends when the container calls the ejbRemove() method. This makes the message bean's state change back to the Does Not Exist state.

When should you use message beans? In general, message beans are useful for receiving messages asynchronously (no waiting). You should consider using a message bean to decouple a client who cannot tolerate waiting for a lengthy business method to complete. A message bean that sends an e-mail confirmation to a large group of recipients is a good example.

The J2EE application server uses JMS to implement message-driven beans. A message bean is relatively easy to implement, since the container does most of the setup work that JMS requires.

Clients and Interfaces

A well-designed interface is important in enterprise programming because it represents the client's view of an enterprise bean. Clients invoke business methods in a session bean or an entity bean only through a bean's interface. This approach allows the EJB container to intercept client calls made through the EJB interface. The container can then perform any required system processing (such as transaction management) before forwarding the call to the method inside the EJB implementation class.

Two types of interfaces are possible with session and entity beans. Let's find out what they are and how you might use them. (Note that message-driven beans do not have client interfaces since access is only through the JMS server.)

Home and Remote Interfaces

Clients may access session and entity beans remotely (from a machine running a different JVM) or locally (within the same JVM). For remote access, session and entity beans have a remote interface and a home interface. These interfaces represent the client's view of an enterprise bean. The remote interface defines a bean's business methods and the home interface defines life cycle methods. The home interface also defines finder and home methods for entity beans. Figure 2–8 shows the home and remote interfaces for a Customer EJB entity bean that has remote access.

Figure 1-8Figure 2—8 Interfaces for Remote Access

Remote clients can be web components, J2EE application clients, or other enterprise beans. Remote clients may execute on one machine, and the enterprise bean it uses may run on a different machine. You must create both a remote interface and a home interface for a client to have remote access to the bean.

Local Home and Local Interfaces

Clients may also interact with session or entity beans locally. This means a local client executes on the same machine as the enterprise bean it uses. Local clients can be web components or other enterprise beans, but not J2EE client applications. A common use of local interfaces is among related entity beans (entity beans with relationship fields to other entity beans). Also, you can construct a business process session bean as a front end (a session facade) to one or more entity beans. The session bean would typically use local access to the entity beans. (See "Session Facade Pattern" on page 250 as well as "Session Facade Pattern" on page 329 for the description, motivation, and implementation of this important design pattern.)

To have local access, you must create a local interface with business m_ethods and a local home interface with life cycle and finder methods. A local interface is also the only way to have entity beans communicate with other entity beans in container-managed relationships. In an abstract schema, any entity bean that is the target of a container-managed relationship field must have a local interface. Figure 2–9 shows the local home and local interfaces for a Customer EJB entity bean with local access.

Figure 1-9Figure 2—9 Interfaces for Local Access

The primary reason for using local interfaces is increased performance. With local access to session or entity beans, method calls execute faster than remote calls, since both client and bean execute under control of the same EJB container.

  • + Share This
  • 🔖 Save To Your Account

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