Java Enterprise Edition (Java EE) has a powerful facility dedicated to expressing the business logic of an application and for accessing a database using a JavaBeans-like concept. That facility is Enterprise JavaBeans, known as EJBs for short.
In this article, we'll begin exploring the world of EJBs, which is a very important capability of the Java EE platform. EJBs provide infrastructure for developing and deploying mission-critical, enterprise applications. We'll first look at some EJB fundamentals, and then focus on one type of EJB: the session bean.
In this article, you will learn the following:
- The benefits of using EJBs
- The three kinds of EJBs: session, entity, and message-driven beans
- The makeup of session beans
- How to develop session beans
- Differences between stateful and stateless session beans
Application architectures often consist of several tiers that each has its own responsibilities. One such architecture that consists of three tiers is illustrated in the Unified Modeling Language (UML) diagram shown in Figure 1.
The two elements on the left side of the diagram in Figure 1 are called components in the UML notation. Components represent software modules. The diagram describes what is called a multitiered, or layered, architecture. Multitiered architectures have many advantages, not the least of which is the ability to change any one of the layers without affecting all of the other layers. This is in contrast to a single-tier architecture, within which all aspects of the program design coexist in a single element. Changes or actions that affect one portion of the single-tier element also potentially affect the other members of that element.
Consider the three-layer architecture shown in Figure 1, consisting of user interface, application logic, and database layers. If the database layer is changed, only the application logic layer is affected. The application logic layer shields the user interface layer from changes to the database layer. This facilitates ongoing maintenance of the application and also increases the application's ability to incorporate new technologies in its layers.
These layers provide an excellent model of how EJBs fit into your overall program design. EJBs provide an application logic layer and a JavaBeans-like abstraction of the database layer. The application logic layer is also known as the middle tier.
|JavaBeans and Enterprise JavaBeans are two different things, but because of their similarities (and for marketing reasons), they share a common name. JavaBeans are components built in Java that can be used on any tier in an application. They are often thought of in relationship to servlets and as GUI components. Enterprise JavaBeans are special, server-based components, used for building the business logic and data access functionality of an application.|
Why use EJBs?
Not too long ago, when system developers wanted to create an enterprise application, they would often start by "rolling their own" (or purchasing a proprietary) application server to support the functionality of the application logic layer. Some of the features of an application server include the following:
- Client communication: The client, which is often a user interface, must be able to call the methods of objects on the application server via agreed-upon protocols.
- Session state management: You'll recall our discussions on this topic in the context of JSP (JavaServer Pages) and servlet development back in Chapter 6.
- Transaction management: Some operations, for example, when updating data, must occur as a unit of work. If one update fails, they all should fail.
- Database connection management: An application server must connect to a database, often using pools of database connections for optimizing resources.
- User authentication and role-based authorization: Users of an application must often log in for security purposes. The functionality of an application to which a user is allowed access is often based on the role associated with a user ID.
- Asynchronous messaging: Applications often need to communicate with other systems in an asynchronous manner; that is, without waiting for the other system to respond. This requires an underlying messaging system that provides guaranteed delivery of these asynchronous messages.
- Application server administration: Application servers must be administered. For example, they need to be monitored and tuned.
The EJB specification
The EJB specification defines a common architecture, which has prompted several vendors to build application servers that comply with this specification. Now developers can get off-the-shelf application servers that comply with a common standard, benefiting from the competition (in areas such as price, features, and performance) among those vendors.
Some of the more common commercial EJB application servers are WebLogic (BEA), Java Enterprise System (Sun), OC4J containers for Oracle Database 10g, and WebSphere (IBM). There are also some very good open source entries in this market such as JBoss and JOnAS. Sun also provides an open source reference implementation (Java EE SDK) of the Java EE 5 and EJB 3.0 specifications that developers can use to develop and test applications for compliance with those specifications. (The reference implementation may not, however, be used to deploy production systems.) Currently under development, the reference implementation is codenamed "Glassfish." The platform provides a basic EJB 3.0 test platform; more details can be found on the Website and in the related discussion forums. These application servers, in conjunction with the capabilities defined in the EJB specification, support all of the features listed here and many more.
The EJB specification was created by experienced members of the development community; such a body is called an expert group. In the EJB specification's expert group are members from such organizations as JBoss, Oracle, and Google. Thanks to them, we now have a standard, specifications-based way to develop and deploy enterprise-class systems. We are approaching the Java dream of developing an application that can run on any vendor platform as-is. This is in contrast to the vendor-specific way we used to develop, where each server had its own way of doing things, and where the developer was locked into the chosen platform once the first line of code was written!
The version of the EJB specification that is included with the Java EE 5.0 recommendation is 3.0, and this is the version we refer to when discussing EJBs. The EJB 3.0 specification has added many improvements to its predecessor (version 2.1, which was a part of the J2EE 1.4 recommendation), including metadata annotations to simplify deployment concerns, a higher degree of control over bean persistence, and a much more simplified (but no less powerful) programming model for developing EJBs.
The three kinds of EJBs
There are actually three kinds of EJBs: session beans, entity beans, and message-driven beans. Here, we will present a brief introduction to each type of bean. The balance of this article will then focus on session beans.
|When referring to EJBs in the general sense, we'll use the term EJBs, enterprise beans, or simply beans.|
One way to think about the application logic layer (middle tier) in the sample architecture shown in Figure 1 is as a set of objects that, together, implement the business logic of an application. Session beans are the construct in EJBs designed for this purpose. As shown in Figure 2, there may be multiple session beans in an application. Each handles a subset of the application's business logic.
A session bean tends to be responsible for a group of related functionality. For example, an application for an educational institution might have a session bean whose methods contain logic for handling student records. Another session bean might contain logic that maintains the lists of courses and programs available at that institution.
There are two types of session beans, which are defined by their use in a client interaction:
- Stateless: These beans do not declare any instance (class-level) variables, so that the methods contained within can act only on any local parameters. There is no way to maintain state across method calls.
- Stateful: These beans can hold client state across method invocations. This is possible with the use of instance variables declared in the class definition. The client will then set the values for these variables and use these values in other method calls.
There may be more work involved for the server to share stateful session beans than is required to share stateless beans. Storing the state of an EJB is a very resource-intensive process, so an application that uses stateful beans may not be easily scalable. Stateless session beans provide excellent scalability, because the EJB container does not need to keep track of their state across method calls. You'll see how to develop both stateless and stateful session beans later in this article.
All EJBs, session beans included, operate within the context of an EJB server, as shown in Figure 2. An EJB server contains constructs known as EJB containers, which are responsible for providing an operating environment for managing and providing services to the EJBs that are running within it.
In a typical scenario, the user interface (UI) of an application calls the methods of the session beans as it requires the functionality that they provide. Session beans can call other session beans and entity beans. Figure 2 illustrates typical interactions between the user interface, session beans, entity beans, and the database.
Before object orientation became popular, programs were usually written in procedural languages and often employed relational databases to hold the data. Because of the strengths and maturity of relational database technology, it is now often advantageous to develop object-oriented applications that use relational databases. The problem with this approach is that there is an inherent difference between object-oriented and relational database technologies, making it less than natural for them to coexist in one application. The use of entity beans is one way to get the best of both of these worlds, for the following reasons:
- Entity beans are objects, and they can be designed using object-oriented principles and used in applications as objects.
- The data in these entity bean objects are persisted in some data store, usually relational databases. All of the benefits of relational technologies—including maturity of products, speed, reliability, ability to recover, and ease of querying—can be leveraged.
In a typical EJB scenario, when a session bean needs to access data, it calls the methods of an entity bean. Entity beans represent the persistent data in an EJB application. For example, an application for an educational institution might have an entity bean named
Student that has one instance for every student that is enrolled in an institution. Entity beans, often backed by a relational database, read and write to tables in the database. Because of this, they provide an object-oriented abstraction to some information store.
As shown in Figure 2, it is a good practice to call only session beans directly from the client, and to let the session beans call the entity beans. Here are some reasons for this:
- This practice doesn't circumvent the business logic contained in the session beans. Calling entity beans directly tends to push the business logic into the UI logic, which is usually a bad thing.
- The UI doesn't need to be as dependent on changes to the entity beans. The UI is shielded from these changes by the session beans.
- In order for a client to interact with a bean on the EJB server, there must be a remote reference to the bean, which takes resources. There tends to be far more (orders of magnitude) entity bean instances in an application than session bean instances. Restricting client access to session beans conserves server and network resources considerably.
|Developing entity beans does not require a business interface; in fact, message-driven beans are the only EJBs that must implement some business interface.|
When an EJB-based application needs to receive asynchronous messages from other systems, it can leverage the power and convenience of message-driven beans. Asynchronous messages between systems can be analogous to the events that are fired from a UI component to an event handler in the same JVM. For example, in the business-to-business (B2B) domain, a wholesaler could have an EJB application that uses message-driven beans to listen for purchase orders issued electronically from retailers.
Which type of EJB should you use?
So, how do you decide whether a given EJB should be a session bean, entity bean, or a message-driven bean? Here are some guidelines for deciding: