Java EJB Introduction to EJBs

Introduction to EJBs


This is the first of four installments that make up Chapter 4: Introduction to EJBs from the book Sams Teach Yourself J2EE in 21 Days (ISBN:0-672-32384-2) written by Martin Bond, Dan Haywood, Debbie Law, Andy Longshaw, and Peter Roxburgh, published by Sams Publishing.


Day 4: Introduction to EJBs

J2EE provides different types of components for different purposes. Today,
you will start to look at one of the principal types of component in
J2EE—Enterprise JavaBeans (EJBs).

The study of EJBs is continued on Day 5, "Session EJBs,", Day 6,
"Entity EJBs", Day 7, "CMP and EJB QL", Day 8,
"Transactions and Persistence", and Day 10, "Message-Driven
Beans". As you can see, there is a lot to learn about EJBs, so today serves
as a first step on the road to all of this EJB knowledge.

Today, you will

  • Examine the different types of EJB available

  • Take a look at how EJBs are applied

  • Explore the structure of one of the EJBs that forms part of the case
    study to see how the different parts fit together

  • Deploy and use some of the EJBs from the case study

  • Write a simple client for an EJB

First, you need to understand why you would use EJBs.

What Is an EJB?

In a typical J2EE application, Enterprise JavaBeans (EJBs) contain the
application's business logic and live business data. Although it is
possible to use standard Java objects to contain your business logic and
business data, using EJBs addresses many of the issues you would find by using
simple Java objects, such as scalability, lifecycle management, and state
management.

Beans, Clients, Containers, and Servers

An EJB is essentially a managed component that is created, controlled, and
destroyed by the J2EE container in which it lives. This control allows the
container to control the number of EJBs currently in existence and the resources
they are using, such as memory and database connections. Each container will
maintain a pool of EJB instances that are ready to be assigned to a client. When
a client no longer needs an EJB, the EJB instance will be returned to the pool
and all of its resources will be released. At times of heavy load, even EJB
instances that are still in use by clients will be returned to the pool so they
can service other clients. When the original client makes another request of its
EJB, the container will reconstitute the original EJB instance to service the
request. This pooling and recycling of EJB instances means that a few EJB
instances, and the resources they use, can be shared between many clients. This
maximizes the scalability of the EJB-based application. The EJB lifecycle is
discussed further on Days 5 and 6.

The client that uses the EJB instance does not need to know about all of this
work by the container. As far as the client is concerned, it is talking to a
remote component that supports defined business methods. How those methods are
implemented and any magic performed by the container, such as just-in-time
instantiation of that specific component instance, are entirely transparent to
the client part of the application.

The EJB benefits from certain services provided by the container, such as
automatic security, automatic transactions, lifecycle management, and so on. To
do this, the EJB must conform to certain rules and implement an appropriate
interface that allows the container to manage the component. The EJB is packaged
with configuration information that indicates the component's requirements,
such as transaction and security requirements. The container will then use this
information to perform authentication and control transactions on behalf of the
component—the component does not have to contain code to perform such
tasks.

The primary purpose of the container is to control and provide services for
the EJBs it contains. When it needs to use some underlying functionality, such
as creating a transaction on behalf of a bean, it uses the facilities of the
underlying EJB server. The EJB server is the base set of services on top of
which the container runs. Different types of EJB will run in different
containers, but many different EJB containers can run on a single EJB server.
EJB servers are generally delivered as part of a J2EE-compliant application
server (examples include BEA WebLogic and IBM WebSphere). You will install and
run the application server, which will provide the underlying services required
of an EJB server and will host EJB containers.

The EJB Landscape

As you have seen, the J2EE Blueprints
(http://java.sun.com/blueprints/enterprise/index.html)
define a target architecture for a typical J2EE-based application. In this
architecture, EJBs live in the middle tier and are used by other application
components that live in the presentation tier. Although it is possible that both
of these logical tiers will reside on the same computer, it is most likely that
they will reside on different machines. This means that an EJB will usually have
to be made available to remote clients.

To offer services to remote clients, EJBs will export their services as RMI
remote interfaces. RMI allows you to define distributed interfaces in Java.
There are certain caveats on doing this, not only at the implementation level
(such as declaring that RemoteExceptions may be thrown when calling a
method on an EJB) but also at the design level. Designing remote interfaces is a
skill in itself, which will be explored as you progress through topics in this
book, such as EJBs and J2EE Patterns.

Because they must use an RMI-based interface to access the functionality of
the EJB, the clients of an EJB must have some programming functionality. This
means that they are typically either "thick" clients that provide a
GUI interface or Web-server components that deliver HTML interfaces to
"thin" clients. The different types of client are explored in more
detail shortly.

In the other direction, EJBs themselves will make use of data sources, such
as databases and mainframe systems, to perform the required business logic.
Access to such data and services can be through a JDBC database connection, a
J2EE Connector, another EJB, or a dedicated server or class of some form.

Discovering EJBs

While it is quite easy to draw pictures of a 3-tier system containing boxes
labelled "EJB," it is important to identify what application
functionality should go into an EJB.

At the start of application development, regardless of the precise
development process used (Rational Unified Process (RUP), eXtreme Programming
(XP), and so on), there is generally some analysis that delivers a Unified
Modelling Language (UML) domain model (this identifies the main elements of the
business problem to be solved). This can then form the basis of a solution model
where the business concepts are mapped into appropriate design-level artefacts,
such as components. This is where EJBs come into the design.

The UML model will consist of a set of classes and packages that represent
single or grouped business concepts. A class or package can be implemented as an
EJB. Generally, only larger individual classes will become EJBs in themselves,
because EJBs are intended to be fairly coarse-grained components that
incorporate a reasonably large amount of functionality and/or data.

There are generally two types of functionality discovered during
analysis—data manipulation and business process flow. The application model
will usually contain data-based classes such as Customer or
Product. These classes will be manipulated by other classes or roles
that represent business processes, such as Purchaser or
CustomerManager. There are different types of EJB that can be applied
to these different requirements.

Types of EJB

There are three different types of EJB that are suited to different
purposes:

  • Session EJB—A Session EJB is useful for mapping business
    process flow (or equivalent application concepts). There are two sub-types of
    Session EJB — stateless and stateful— that are discussed in more
    detail on Day 5. Session EJBs commonly represent "pure" functionality
    that is created as it is needed.

  • Entity EJB—An Entity EJB maps a combination of data (or
    equivalent application concept) and associated functionality. Entity EJBs are
    usually based on an underlying data store and will be created based on that data
    within it.

  • Message-driven EJB—A Message-driven EJB is very similar in
    concept to a Session EJB, but is only activated when an asynchronous message
    arrives.

As an application designer, you should choose the most appropriate type of
EJB based on the task to be accomplished.

Common Uses of EJBs

So, given all of this, where would you commonly encounter EJBs and in what
roles? Well, the following are some examples:

  • In a Web-centric application, the EJBs will provide the business logic
    that sits behind the Web-oriented components, such as servlets and JSPs. If a
    Web-oriented application requires a high level of scalability or
    maintainability, use of EJBs can help to deliver this.

  • Thick client applications, such as Swing applications, will use EJBs in a
    similar way to Web-centric applications. To share business logic in a natural
    way between different types of client applications, EJBs can be used to house
    that business logic.

  • Business-to-business (B2B) e-commerce applications can also take
    advantage of EJBs. Because B2B e-commerce frequently revolves around the
    integration of business processes, EJBs provide an ideal place to house the
    business process logic. They can also provide a link between the Web
    technologies frequently used to deliver B2B and the business systems
    behind.

  • Enterprise Application Integration (EAI) applications can incorporate
    EJBs to house processing and mapping between different applications. Again, this
    is an encapsulation of the business logic that is needed when transferring data
    between applications (in this case, in-house applications).

These are all high-level views on how EJBs are applied. There are various
other EJB-specific patterns and idioms that can be applied when implementing
EJB-based solutions. These are discussed more on Day 18,
"Patterns."

Given this context, common types of EJB client include the following:

  • A servlet or JSP that provides an HTML-based interface for a browser
    client

  • Another EJB that can delegate certain of its own tasks or can work in
    combination with other EJBs to achieve its own goals

  • A Java/Swing application that provides a front-end for the business
    processes encapsulated in the EJB

  • A CORBA application that takes advantage of the EJB's business
    logic

  • An applet that takes advantage of the business logic in a remote EJB so
    that this business logic does not need to be downloaded to the client

These are common ways that EJBs are applied. What benefits does the use of
EJBs give to you as a developer?

Why Use EJBs?

Despite the recommendations of the J2EE Blueprints, the use of EJBs is not
mandatory. You can build very successful applications using servlets, JSPs or
standalone Java applications.

As a general rule of thumb, if an application is small in scope and is not
required to be highly scalable, you can use J2EE components, such as servlets,
together with direct JDBC connectivity to build it. However, as the application
complexity grows or the number of concurrent users increases, the use of EJBs
makes it much easier to partition and scale the application. In this case, using
EJBs gives you some significant advantages.

Hiding Complexity

Early middleware environments, such as "raw" CORBA, require the
application developer to write a lot of code that interacts with the CORBA
environment and facilitates the connectivity and registration process. Such code
can be likened to the plumbing that pipes water around a house. It needs to be
there but, as the user of a sink or shower, you do not want to be intimately
involved with it. In J2EE application terms, business developers want to write
business code, not "plumbing" code. The EJB model tries to reduce such
interaction to a minimum by using the following mechanisms:

  • Each bean conforms to a defined lifecycle and set of rules. This provides
    a distinct boundary between system code and application code.

  • Declarative attributes allow a developer to specify, say, the
    transactional behavior of the component without having to write code to control
    such functionality.

  • The deployment information provided with the deployable J2EE application
    provides information about the relationships between multiple EJBs and also
    defines the resources required by an EJB.

Separation of Business Logic from UI and Data
Access

One of the key facets of applying EJBs is that they allow business functionality
to be developed and then deployed independently of the presentational layer.
You might, for example, create an application with a user interface built using
Java's Swing API. This application might then provide access to some business
functionality for the employees working on the company's internal network.
If the underlying business functionality is implemented using EJBs, a different
user interface could take its place without having to redevelop the entire application.
A Web-based interface that used servlets would make the application available
from the Internet without having to change a single line of code in the business
functionality. Figure 4.1 is a UML component
diagram that shows this. (More information on UML can be found in Appendix A,
"An Introduction to UML," on the accompanying CD-ROM.)

It can sometimes be difficult to distinguish between the functionality that
an application provides and the user interface that is used to invoke that
functionality. This is not unexpected because many common applications—such
as a word-processor—are single-tier; the presentational logic and the
business functionality are a single entity. On the other hand, consider
programming a video recorder. Most modern video recorders can be programmed
either directly on the console or through a remote control unit. Either user
interface will accomplish the task of recording your favorite TV show, but there
is only a single "application."

Figure 4.1: An application implemented using EJBs can have more than one user interface.

Consider another example. In most supermarkets, a cashier is responsible for
scanning the items in your shopping cart and then requesting a payment for the
total. However, some supermarkets also offer a trust system, whereby the
customer scans the items with a mobile scanner as they place the item into the
shopping cart. To pay for the goods in the shopping cart, the customer
simply swipes his or her own card, and then leaves with the goods. Again, there
is a single application (to purchase shopping items) but two different
interfaces—the cashier's till and the customer's mobile
scanner.

To implement a distributed application using EJBs, make sure you have
distinguished between the user interface and the underlying business function.
The EJB itself is concerned only with the latter of these.

Container Services

The container provides various services for the EJB to relieve the developer
from having to implement such services, namely

  • Distribution via proxies—The container will generate a
    client-side stub and server-side skeleton for the EJB. The stub and skeleton
    will use RMI over IIOP to communicate.

  • Lifecycle management—Bean initialization, state management,
    and destruction is driven by the container, all the developer must do is
    implement the appropriate methods.

  • Naming and registration—The EJB container and server will
    provide the EJB with access to naming services. These services are used by local
    and remote clients to look up the EJB and by the EJB itself to look up resources
    it may need.

  • Transaction management—Declarative transactions provide a
    means for the developer to easily delegate the creation and control of
    transactions to the container.

  • Security and access control—Again, declarative security
    provides a means for the developer to easily delegate the enforcement of
    security to the container.

  • Persistence (if you want)—Using the Entity EJB's
    container-managed persistence mechanism, state can be saved and restored without
    having to write a single line of code.

All of these container services are covered in more detail as the book
progresses.

Now that you know why you would want to use an EJB and how to apply it, you
can examine the inner workings of an EJB to understand how all the parts fit
together.

Tuesday’s installment: What’s in an EJB?


About the Author

Andy Longshaw is a consultant, writer and educator specializing in J2EE, XML, Web-based technologies and components, particularly the design and architecture decisions required to use these technologies successfully. Andy has been explaining technology for most of the last decade as a trainer and in conference sessions. A wild rumor suggests that some people have managed to stay awake in these sessions. Despite being well educated and otherwise fairly normal, Andy still subjects himself, and his family, to “trial by unpredictability” by watching Manchester City FC far more often than is healthy.

Andy and the other authors work for Content Master Ltd., a technical authoring company in the United Kingdom specializing in the production of training and educational materials. For more information on Content Master, please see their web site at www.contentmaster.com

Source of this material

This is the first of four installments that make up Chapter 4: Introduction to EJBs from the book Sams Teach Yourself J2EE in 21 Days (ISBN:0-672-32384-2) written by Martin Bond, Dan Haywood, Debbie Law, Andy Longshaw, and Peter Roxburgh, published by Sams Publishing.

To access the full Table of Contents for the book

Latest Posts

Related Stories