BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Enterprise JavaBeans
Enterprise JavaBeans, Third Edition By Richard Monson-Haefel
September 2001
Pages: 590

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
This book is about Enterprise JavaBeans 2.0 and 1.1, which are the third and second versions of the Enterprise JavaBeans specification. Just as the Java platform has revolutionized the way we think about software development, Enterprise JavaBeans has revolutionized the way we think about developing mission-critical enterprise software. It combines server-side components with distributed object technologies and asynchronous messaging to greatly simplify the task of application development. It automatically takes into account many of the requirements of business systems, including security, resource pooling, persistence, concurrency, and transactional integrity.
This book shows you how to use Enterprise JavaBeans to develop scalable, portable business systems. But before we can start talking about EJB itself, we'll need a brief introduction to the technologies addressed by EJB, such as component models, distributed objects, component transaction monitors (CTMs), and asynchronous messaging. It's particularly important to have a basic understanding of component transaction monitors, the technology that lies beneath EJB. In Chapter 2 and Chapter 3, we'll start looking at EJB itself and see how enterprise beans are put together. The rest of this book is devoted to developing enterprise beans for an imaginary business and discussing advanced issues.
It is assumed that you're already familiar with Java; if you're not, Learning Java™, by Patrick Niemeyer and Josh Peck (O'Reilly), is an excellent introduction. This book also assumes that you're conversant in the JDBC API, or at least in SQL. If you're not familiar with JDBC, see Database Programming with JDBC™ and Java™ by George Reese (O'Reilly).
One of Java's most important features is platform independence. Since it was first released, Java has been marketed as "write once, run anywhere." While the hype has gotten a little heavy-handed at times, code written with Sun's Java programming language is remarkably platform independent. Enterprise JavaBeans isn't just platform independent—it's also implementation independent. If you've worked with JDBC, you know a little about what this means. Not only can the JDBC API run on a Windows machine or on a Unix machine, it can also access relational databases of many different vendors (DB2, Oracle, Sybase, SQLServer, etc.) by using different JDBC drivers. You don't have to code to a particular database implementation—just change JDBC drivers and you change databases. It's the same with EJB. Ideally, an EJB component, an enterprise bean, can run in any application server that implements the EJB specification. This means that you can develop and deploy your EJB business system in one server, such as Orion or BEA's WebLogic, and later move it to a different EJB server, such as Pramati, Sybase EAServer, IBM's WebSphere, or an open source project such as OpenEJB, JOnAS, or JBoss. Implementation independence means that your business components are not dependent on the brand of server, which gives you many more options before, during, and after development and deployment.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting the Stage
Before defining Enterprise JavaBeans more precisely, let's set the stage by discussing a number of important concepts: distributed objects, business objects, component transaction monitors, and asynchronous messaging.
Distributed computing allows a business system to be more accessible. Distributed systems allow parts of the system to be located on separate computers, possibly in many different locations, where they make the most sense. In other words, distributed computing allows business logic and data to be reached from remote locations. Customers, business partners, and other remote parties can use a business system at any time from almost anywhere. The most recent development in distributed computing is distributed objects . Distributed object technologies such as Java RMI, CORBA, and Microsoft's .NET allow objects running on one machine to be used by client applications on different computers.
Distributed objects evolved from a legacy form of three-tier architecture used in transaction processing (TP) monitor systems such as IBM's CICS and BEA's TUXEDO. These systems separate the presentation, business logic, and database into three distinct tiers (or layers). In the past, these legacy systems were usually composed of a "green screen" or dumb terminal for the presentation tier (first tier), COBOL or PL/1 applications as the middle tier (second tier), and some sort of database, such as DB2, as the backend (third tier). The introduction of distributed objects in recent years has given rise to a new form of three-tier architecture. Distributed object technologies make it possible to replace the procedural COBOL and PL/1 applications on the middle tier with business objects. A three-tier distributed-business-object architecture might have a sophisticated graphical or web-based interface on the first tier, business objects on the middle tier, and a relational or some other database on the backend. More complex architectures often have many tiers: different objects reside on different servers and interact to get the job done. Creating these
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enterprise JavaBeans Defined
Sun Microsystems' definition of Enterprise JavaBeans is:
The Enterprise JavaBeans architecture is a component architecture for the development and deployment of component-based distributed business applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and multi-user secure. These applications may be written once, and then deployed on any server platform that supports the Enterprise JavaBeans specification.
That's a mouthful, but it's not atypical of how Sun defines many of its Java technologies—have you ever read the definition of the Java language itself? It's about twice as long. This book offers a shorter definition of EJB:
Enterprise JavaBeans is a standard server-side component model for component transaction monitors.
We have already set the stage for this definition by briefly defining the terms "distributed objects," "server-side components," and "component transaction monitors." To provide you with a complete and solid foundation for learning about Enterprise JavaBeans, this chapter will now expand on these definitions.
If you already have a clear understanding of distributed objects, transaction monitors, CTMs, and asynchronous messaging, feel free to skip the rest of this chapter and move on to Chapter 2.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Distributed Object Architectures
EJB is a component model for component transaction monitors, which are based on distributed object technologies. Therefore, to understand EJB you need to understand how distributed objects work. Distributed object systems are the foundation for modern three-tier architectures. In a three-tier architecture, as shown in Figure 1-1, the presentation logic resides on the client (first tier), the business logic resides on the middle tier (second tier), and other resources, such as the database, reside on the backend (third tier).
Figure 1-1: Three-tier architecture
All distributed object protocols are built on the same basic architecture, which is designed to make an object on one computer look like it's residing on a different computer. Distributed object architectures are based on a network communication layer that is really very simple. Essentially, there are three parts to this architecture: the business object, the skeleton, and the stub.
The business object resides on the middle tier. It's an instance of an object that models the state and business logic of some real-world concept, such as a person, order, or account. Every business object class has matching stub and skeleton classes built specifically for that type of business object. So, for example, a distributed business object called Person would have matching Person_Stub and Person_Skeleton classes. As shown in Figure 1-2, the business object and skeleton reside on the middle tier, and the stub resides on the client.
The stub and the skeleton are responsible for making the business object on the middle tier look as if it is running locally on the client machine. This is accomplished through some kind of remote method invocation ( RMI) protocol. An RMI protocol is used to communicate method invocations over a network. CORBA, Java RMI, and Microsoft .NET all use their own RMI protocols. Every instance of the business object on the middle tier is wrapped by an instance of its matching skeleton class. The skeleton is set up on a port and IP address and listens for requests from the stub, which resides on the client machine and is connected via the network to the skeleton. The stub acts as the business object's surrogate on the client and is responsible for communicating requests from the client to the business object through the skeleton. Figure 1-2 illustrates the process of communicating a method invocation from the client to the server object and back. The stub and the skeleton hide the communication specifics of the RMI protocol from the client and the implementation class, respectively.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Component Models
The term "component model" has many different interpretations. Enterprise JavaBeans specifies a server-side component model. Using a set of classes and interfaces from the javax.ejb package, developers can create, assemble, and deploy components that conform to the EJB specification.
The original JavaBeans™ is also a component model, but it's not a server-side component model like EJB. In fact, other than sharing the name "JavaBeans," these two component models are completely unrelated. In the past, a lot of the literature referred to EJB as an extension of the original JavaBeans, but this is a misrepresentation. The two APIs serve very different purposes, and EJB does not extend or use the original JavaBeans component model.
JavaBeans is intended to be used for intraprocess purposes, while EJB is designed for inter process components. In other words, the original JavaBeans was not intended for distributed components. JavaBeans can be used to solve a variety of problems, but it is primarily used to build clients by assembling visual (GUI) and nonvisual widgets. It's an excellent component model, possibly the best one ever devised for intraprocess development, but it's not a server-side component model. EJB, on the other hand, is explicitly designed to address issues involved with managing distributed business objects in a three-tier architecture.
Given that JavaBeans and Enterprise JavaBeans are completely different, why are they both called component models? In this context, a component model defines a set of contracts between the component developer and the system that hosts the component. The contracts express how a component should be developed and packaged. Once a component is defined, it becomes an independent piece of software that can be distributed and used in other applications. A component is developed for a specific purpose but not a specific application. In the original JavaBeans, a component might be a push button or a spreadsheet that can be used in any GUI application according to the rules specified in the original JavaBeans component model. In EJB, a component might be a customer business object that can be deployed in any EJB server and used to develop any business application that needs a customer business object. Other types of Java component models include servlets, JSP pages ( JSPs), and applets.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Component Transaction Monitors
The CTM industry grew out of both the ORB and TP monitor industries. The CTM is really a hybrid of these two technologies that provides a powerful, robust distributed object platform. To better understand what a CTM is, we will examine the strengths and weakness of TP monitors and ORBs.
Transaction processing (TP) monitors have been evolving for about 30 years (CICS, the Customer Information Control System, was introduced in 1968) and have become powerful, high-speed server platforms for mission-critical applications. Some TP products, such as CICS and TUXEDO, may be familiar to you. TP monitors are operating systems for business applications written in languages such as COBOL. It may seem strange to call a TP monitor an "operating system," but because it controls an application's entire environment, it's a fitting description. TP monitor systems automatically manage the entire environment in which a business application runs, including transactions, resource management, and fault tolerance. The business applications that run in TP monitors are written in procedural programming languages (e.g., COBOL and C) that are often accessed through network messaging or remote procedure calls (RPCs). Messaging allows a client to send a message to a TP monitor requesting that some application be run with certain parameters. It's similar in concept to the Java event model. Messaging can be synchronous or asynchronous, meaning that the sender may or may not be required to wait for a response. RPC, which is the ancestor of RMI, is a distributed mechanism that allows clients to invoke procedures on applications in a TP monitor as though the procedures were executed locally. The primary difference between RPC and RMI is that RPC is used for procedure-based applications and RMI is used for distributed object systems. With RMI, methods can be invoked on a specific object identity; i.e., a specific business entity. In RPC, a client can call procedures on a specific type of application, but there is no concept of object identity. RMI is object-oriented; RPC is procedural.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
CTMs and Server-Side Component Models
CTMs require that business objects adhere to the server-side component model implemented by the vendor. A good component model is critical to the success of a development project because it defines how easily an application developer can write business objects for the CTM. The component model is a contract that defines the responsibilities of the CTM and the business objects. With a good component model, a developer knows what to expect from the CTM, and the CTM understands how to manage the business object. Server-side component models are great at describing the responsibilities of the application developer and CTM vendor.
Server-side component models are based on a specification. As long as the component adheres to the specification, it can be used by the CTM. The relationship between the server-side component and the CTM is like the relationship between a CD-ROM and a CD player. As long as the component (CD-ROM) adheres to the player's specifications, you can play it.
A CTM's relationship with its component model is also similar to the relationship the railway system has with trains. The railway system manages the train's environment, providing alternate routes for load balancing, multiple tracks for concurrency, and a traffic-control system for managing resources. The railway provides the infrastructure on which trains run. Similarly, a CTM provides server-side components with the entire infrastructure needed to support concurrency, transactions, load balancing, etc.
Trains on the railway are like server-side components: they all perform different tasks but they do so using the same basic design. The train focuses on performing a task, such as moving cars, not on managing the environment. For the engineer, the person driving the train, the interface for controlling the train is fairly simple: a brake and a throttle. For the application developer, the interface to the server-side component is similarly limited.
Different CTMs may implement different component models, just as different railways have different kinds of trains. The differences between the component models vary, like railway systems having different track widths and different controls, but the fundamental operations of CTMs are the same. They all ensure that business objects are managed so that they can support large populations of users in mission-critical situations. This means that resources, concurrency, transactions, security, persistence, load balancing, and distribution of objects can be handled automatically, limiting the application developer to a simple interface. This allows the application developer to focus on the business logic instead of the enterprise infrastructure.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Titan Cruises: An Imaginary Business
To make things a little easier, and more fun, we will discuss all the concepts in this book in the context of one imaginary business, a cruise line called Titan. A cruise line makes a particularly interesting example because it incorporates several different businesses: it has ship cabins that are similar to hotel rooms, it serves meals like a restaurant, it offers various recreational opportunities, and it needs to interact with other travel businesses.
This type of business is a good candidate for a distributed object system because many of the system's users are geographically dispersed. Commercial travel agents, for example, who need to book passage on Titan ships will need to access the reservation system. Supporting many—possibly hundreds—of travel agents requires a robust transactional system to ensure that agents have access and that reservations are completed properly.
Throughout this book, we will build a fairly simple slice of Titan's EJB system that focuses on the process of making a reservation for a cruise. This will give us an opportunity to develop Ship, Cabin, TravelAgent, ProcessPayment, and other enterprise beans. In the process, you will need to create relational database tables for persisting data used in the example. It is assumed that you are familiar with relational database management systems and that you can create tables according to the SQL statements provided. EJB can be used with any kind of database or legacy application, but relational databases seem to be the most commonly understood database, so we have chosen this as the persistence layer.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Next?
To develop business objects using EJB, you have to understand the life cycle and architecture of EJB components. This means understanding conceptually how EJB's components are managed and made available as distributed objects. Developing an understanding of the EJB architecture is the focus of the next two chapters.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Architectural Overview
As you learned in Chapter 1, Enterprise JavaBeans is a component model for component transaction monitors, which are the most advanced type of business application servers available today. To effectively use Enterprise JavaBeans, you need to understand the EJB architecture, so this book includes two chapters on the subject. This chapter explores the core of EJB: how enterprise beans are distributed as business objects. Chapter 3 explores the services and resource-management techniques supported by EJB.
To be truly versatile, the EJB component design had to be smart. For application developers, assembling enterprise beans is simple, requiring little or no expertise in the complex system-level issues that often plague three-tier development efforts. While EJB makes the process easy for application developers, it also provides system developers (the people who write EJB servers) with a great deal of flexibility in how they support the EJB specification.
The similarities among different CTMs allow the EJB abstraction to be a standard component model for all of them. Each vendor's CTM is implemented differently, but they all support the same primary services and similar resource-management techniques. These services and techniques are covered in more detail in Chapter 3, but some of the infrastructure for supporting them is addressed in this chapter.
Enterprise JavaBeans server-side components come in three fundamentally different types: entity, session, and message-driven beans. Both session and entity beans are RMI-based server-side components that are accessed using distributed object protocols. The message-driven bean, which is new to EJB 2.0, is an asynchronous server-side component that responds to JMS asynchronous messages.
A good rule of thumb is that entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory, or even a place. In other words, entity beans model real-world objects; these objects are usually persistent records in some kind of database. Our hypothetical cruise line will need entity beans that represent cabins, customers, ships, etc.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Enterprise Bean Component
Enterprise JavaBeans server-side components come in three fundamentally different types: entity, session, and message-driven beans. Both session and entity beans are RMI-based server-side components that are accessed using distributed object protocols. The message-driven bean, which is new to EJB 2.0, is an asynchronous server-side component that responds to JMS asynchronous messages.
A good rule of thumb is that entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory, or even a place. In other words, entity beans model real-world objects; these objects are usually persistent records in some kind of database. Our hypothetical cruise line will need entity beans that represent cabins, customers, ships, etc.
Session beans are an extension of the client application and are responsible for managing processes or tasks. A Ship bean provides methods for doing things directly to a ship but doesn't say anything about the context under which those actions are taken. Booking passengers on the ship requires that we use a Ship bean, but it also requires a lot of things that have nothing to do with the ship itself: we'll need to know about passengers, ticket rates, schedules, and so on. A session bean is responsible for this kind of coordination. Session beans tend to manage particular kinds of activities, such as the act of making a reservation. They have a lot to do with the relationships between different enterprise beans. A TravelAgent session bean, for example, might make use of a Cruise, a Cabin, and a Customer—all entity beans—to make a reservation.
Similarly, message-driven beans in EJB 2.0 are responsible for coordinating tasks involving other session and entity beans. The major difference between a message-driven bean and a session bean is how they are accessed. While a session bean provides a remote interface that defines which methods can be invoked, a message-driven bean does not. Instead, the message-driven bean subscribes to or listens for specific asynchronous messages to which it responds by processing the message and managing the actions other beans take in response to those messages. For example, a ReservationProcessor message-driven bean would receive asynchronous messages—perhaps from a legacy reservation system—from which it would coordinate the interactions of the Cruise, Cabin, and Customer beans to make a reservation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Enterprise Beans
Let's look at how a client would work with an enterprise bean to do something useful. We'll start with the Cabin EJB defined earlier. A cabin is a thing or place whose description is stored in a database. To make the example a little more real, imagine that there are other entity beans: Ship, Cruise, Ticket, Customer, Employee, and so on.
Imagine that a GUI client needs to display information about a particular cruise, including the cruise name, the ship name, and a list of cabins. Using the cruise ID obtained from a text field, we can use some of our beans to populate the GUI with data about the requested cruise. Here's what the code would look like:
CruiseHomeRemote cruiseHome = ... use JNDI to get the home
// Get the cruise ID from a text field.
String cruiseID = textFields1.getText();
// Create an EJB primary key from the cruise ID.
Integer pk = new Integer(cruiseID);
// Use the primary key to find the cruise.
CruiseRemote cruise = cruiseHome.findByPrimaryKey(pk);
// Set text field 2 to show the cruise name.
textField2.setText(cruise.getName());
// Get a remote reference to the ship that will be used
// for the cruise from the cruise bean.
ShipRemote ship = cruise.getShip();
// Set text field 3 to show the ship's name.
textField3.setText(ship.getName());

// Get all the cabins on the ship.
Collection cabins = ship.getCabins();
Iterator cabinItr = cabins.iterator();

// Iterate through the enumeration, adding the name of each cabin
// to a list box.
while( cabinItr.hasNext())
    CabinRemote cabin = (CabinRemote)cabinItr.next();
    listBox1.addItem(cabin.getName());
}
Let's start by getting a remote reference to the EJB home for an entity bean that represents a cruise. We are using a remote reference instead of a local one, because the client is a GUI Java application located outside the EJB container. In EJB 1.1, we don't have a choice because only remote component interfaces are supported. It's not shown in the example, but references to the EJB home are obtained using JNDI. JNDI is a powerful API for locating resources, such as remote objects, on networks. It's a little too complicated to talk about here, but it will be covered in subsequent chapters.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Bean-Container Contract
The environment that surrounds the beans on the EJB server is often referred to as the container. The container is more a concept than a physical construct. Conceptually, the container acts as an intermediary between the bean and the EJB server. It manifests and manages the EJB objects and EJB homes for a particular type of bean and helps these constructs to manage bean resources and apply primary services such as transactions, security, concurrency, naming, and so forth at runtime. Conceptually, an EJB server may have many containers, each of which may contain one or more types of enterprise beans. As you will discover a little later, the container and the server are not clearly different constructs, but the EJB specification defines the component model in terms of the container's responsibilities, so we will follow that convention here.
Enterprise bean components interact with the EJB container through a well-defined component model. The EntityBean, SessionBean , and MessageDrivenBean (EJB 2.0) interfaces are the bases of this component model. As we learned earlier, these interfaces provide callback methods that notify the bean class of life-cycle events. At runtime, the container invokes the callback methods on the bean instance when appropriate life-cycle events occur. When the container is about to write an entity bean instance's state to the database, for example, it first calls the bean instance's ejbStore() method. This provides the bean instance with an opportunity to do some cleanup on its state just before it's written to the database. The ejbLoad() method is called just after the bean's state is populated from the database, providing the bean developer with an opportunity to manage the bean's state before the first business method is called. Other callback methods can be used by the bean class in a similar fashion. EJB defines when these various callback methods are invoked and what can be done within their contexts. This provides the bean developer with a predictable runtime component model.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter covered a lot of ground, describing the basic architecture of an EJB system. At this point, you should understand that beans are business object components. The home interfaces define life-cycle methods for creating, finding, and destroying beans, and the remote and local interfaces define the public business methods of the bean. Message-driven beans do not have component interfaces. The bean class is where the state and behavior of the bean are implemented.
There are three basic kinds of beans: entity, session, and message-driven. Entity beans are persistent and represent a person, place, or thing. Session beans are extensions of the client and embody a process or a workflow that defines how other beans interact. Session beans are not persistent, receiving their state from the client, and they live only as long as the client needs them. Message-driven beans in EJB 2.0 are integration points that allow other applications to interact with EJB applications using JMS asynchronous messaging. Message-driven beans, like stateless session beans, are not persistent and do not maintain conversational state.
The EJB object and EJB home are conceptual constructs that delegate method invocations to session and entity beans from the client and help the container to manage the enterprise bean at runtime. The clients of entity and session beans do not interact with the instances of the bean class directly. Instead, the client software interacts with stubs, which are connected to the EJB object and EJB home. The EJB object implements the remote and/or local interface and expands the bean class's functionality. The EJB home implements the home interface and works closely with the container to create, locate, and remove beans.
Beans interact with their containers through the well-defined bean-container contract. This contract provides callback methods, the EJBContext, and the JNDI environment naming context. The callback methods notify the bean class that it is involved in a life-cycle event. The EJBContext and JNDI environment naming context provide the bean instance with information about its environment. The container-server contract is not well defined and remains proprietary at this time. Future versions of EJB may specify the container-server contract .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Resource Management and the Primary Services
Chapter 2 discussed the basic architecture of Enterprise JavaBeans, including the relationship between the bean class, the component interfaces, the EJB object and EJB home, and the EJB container. These architectural components define a common model for distributed server-side components in component transaction monitors.
One of the reasons why CTMs are such great distributed object platforms is that they do more than just distribute objects: they also manage the resources used by distributed objects. CTMs are designed to manage thousands, even millions, of distributed objects simultaneously. To be this robust, CTMs must be very smart resource managers, managing how distributed objects use memory, threads, database connections, processing power, and more. EJB recognizes that some of the resource-management techniques employed by CTMs are very common, and it defines interfaces that help developers create beans that can take advantage of these common practices.
EJB CTMs are also great distributed object brokers. Not only do they help clients locate the distributed objects they need, but they also provide many services that make it much easier for a client to use the objects correctly. CTMs commonly support six primary services: concurrency, transaction management, persistence, object distribution, naming, and security. These services provide the kind of infrastructure that is necessary for a successful three-tier system.
With the introduction of message-driven beans in EJB 2.0, Enterprise JavaBeans goes beyond most CTMs by expanding the platform's responsibilities to include managing asynchronous messaging components. CTMs have historically been responsible only for managing RMI-based distributed objects. While the method of access is different for message-driven beans, EJB is still responsible for managing the primary services for message-driven beans just as it does for session and entity beans.
This chapter discusses both the resource-management facilities and the primary services that are available to Enterprise JavaBeans.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Resource Management
One of the fundamental benefits of using EJB servers is that they are able to handle heavy workloads while maintaining a high level of performance. A large business system with many users can easily require thousands of objects—even millions of objects—to be in use simultaneously. As the number of interactions among these objects increases, concurrency and transactional concerns can degrade the system's response time and frustrate users. EJB servers increase performance by synchronizing object interactions and sharing resources.
There is a relationship between the number of clients and the number of distributed objects that are required to service them. As client populations increase, the number of distributed objects and resources required increases. At some point, the increase in the number of clients will impact performance and diminish throughput. EJB explicitly supports two mechanisms that make it easier to manage large numbers of beans at runtime: instance pooling and activation.
The concept of pooling resources is nothing new. A commonly used technique is to pool database connections so that the business objects in the system can share database access. This trick reduces the number of database connections needed, which reduces resource consumption and increases throughput. Pooling and reusing database connections is less expensive than creating and destroying connections as needed. Most EJB containers also apply resource pooling to server-side components; this technique is called instance pooling. Instance pooling reduces the number of component instances, and therefore resources, needed to service client requests. It is also less expensive to reuse pooled instances than to frequently create and destroy instances.
As you already know, EJB clients of session and entity beans interact with these types of enterprise beans through the remote and, for EJB 2.0, local interfaces that are implemented by EJB objects. Client applications never have direct access to the actual session or entity bean. Instead, they interact with EJB objects, which wrap bean instances. Similarly, JMS clients in EJB 2.0 never interact with message-driven beans directly. They send messages that are routed to the EJB container system. The EJB container then delivers these messages to the proper message-driven instance.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Primary Services
Many value-added services are available for distributed applications. The OMG (the CORBA governing body), for example, has defined 13 services for use in CORBA-compliant ORBs. This book looks at seven value-added services that are called the primary services, because they are required to complete the Enterprise JavaBeans platform. The primary services include concurrency, transactions, persistence, distributed objects, asynchronous messaging (EJB 2.0), naming, and security.
The seven primary services are not new concepts; the OMG defined interfaces for these services that are specific to the CORBA platform some time ago. In most traditional CORBA ORBs, services are add-on subsystems that are explicitly utilized by the application code. This means that the server-side component developer has to write code to use primary service APIs right alongside their business logic. The use of primary services becomes complicated when they are used in combination with resource-management techniques because the primary services are themselves complex. Using them in combination only compounds the problem.
As more complex component interactions are required, coordinating these services becomes a difficult task, requiring system-level expertise unrelated to the task of writing the application's business logic. Application developers can become so mired in the system-level concerns of coordinating various primary services and resource-management mechanisms that their main responsibility, modeling the business, is all but forgotten.
EJB servers automatically manage all the primary services. This relieves the application developers from the task of mastering these complicated services. Instead, developers can focus on defining the business logic that describes the system and leave the system-level concerns to the EJB server. The following sections describe each of the primary services and explain how they are supported by EJB.
The issue of concurrency is important to all the bean types, but it has a different meaning when applied to EJB 2.0 message-driven beans than it does with the RMI-based session and entity beans. This is because of the difference in context: with RMI-based beans, concurrency refers to multiple clients accessing the same bean simultaneously; with message-driven beans, concurrency refers to the processing of multiple asynchronous messages simultaneously. For this reason, we will discuss the importance of concurrency as a primary service separately for these different types of beans.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Next?
The first three chapters of this book gave you a foundation on which to develop Enterprise JavaBeans components and applications. You should have a better understanding of CTMs and the EJB component model.
Beginning with Chapter 4, you will develop your own beans and learn how to apply them in EJB applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Developing Your First Enterprise Beans
One of the most important features of EJB is that enterprise beans work with containers from different vendors. However, that doesn't mean that selecting a server and installing your enterprise beans on that server are trivial processes.
The EJB server you choose should provide a utility for deploying an enterprise bean. It doesn't matter whether the utility is command-line oriented or graphical, as long as it does the job. The deployment utility should allow you to work with prepackaged enterprise beans, i.e., enterprise beans that have already been developed and archived in a JAR file. Finally, the EJB server should support an SQL-standard relational database that is accessible using JDBC. For the database, you should have privileges sufficient for creating and modifying a few simple tables in addition to normal read, update, and delete capabilities. If you have chosen an EJB server that does not support an SQL-standard relational database, you may need to modify the examples to work with the product you are using.
This book does not say very much about how to install and deploy enterprise beans. That task is largely server-dependent. I'll provide some general ideas about how to organize JAR files and create deployment descriptors, but for a complete description of the deployment process, you'll have to refer to your vendor's documentation or look at the workbook for your vendor.
This chapter provides you with your first opportunities to use a workbook. Throughout the rest of this book, you will see callouts that direct you to exercises in the workbook. A callout will look something like the following:
Please refer to Workbook Exercise 4.2, A Simple Session Bean. This workbook is available free, in PDF format, at http://www.oreilly.com/catalog/entjbeans3/workbooks.
As was mentioned in the Preface, the workbooks can be downloaded in PDF format from
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Choosing and Setting Up an EJB Server
One of the most important features of EJB is that enterprise beans work with containers from different vendors. However, that doesn't mean that selecting a server and installing your enterprise beans on that server are trivial processes.
The EJB server you choose should provide a utility for deploying an enterprise bean. It doesn't matter whether the utility is command-line oriented or graphical, as long as it does the job. The deployment utility should allow you to work with prepackaged enterprise beans, i.e., enterprise beans that have already been developed and archived in a JAR file. Finally, the EJB server should support an SQL-standard relational database that is accessible using JDBC. For the database, you should have privileges sufficient for creating and modifying a few simple tables in addition to normal read, update, and delete capabilities. If you have chosen an EJB server that does not support an SQL-standard relational database, you may need to modify the examples to work with the product you are using.
This book does not say very much about how to install and deploy enterprise beans. That task is largely server-dependent. I'll provide some general ideas about how to organize JAR files and create deployment descriptors, but for a complete description of the deployment process, you'll have to refer to your vendor's documentation or look at the workbook for your vendor.
This chapter provides you with your first opportunities to use a workbook. Throughout the rest of this book, you will see callouts that direct you to exercises in the workbook. A callout will look something like the following:
Please refer to Workbook Exercise 4.2, A Simple Session Bean. This workbook is available free, in PDF format, at http://www.oreilly.com/catalog/entjbeans3/workbooks.
As was mentioned in the Preface, the workbooks can be downloaded in PDF format from
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing an Entity Bean
There seems to be no better place to start than the Cabin EJB, which we have been examining throughout the previous chapters. The Cabin EJB is an entity bean that encapsulates the data and behavior associated with a cruise ship cabin in Titan's business domain.
When developing an entity bean, we first want to define the enterprise bean's remote interface. The remote interface defines the enterprise bean's business purpose; the methods of this interface must capture the concept of the entity. We defined the remote interface for the Cabin EJB in Chapter 2; here, we add two new methods for setting and getting the ship ID and the bed count. The ship ID identifies the ship to which the cabin belongs, and the bed count tells how many people the cabin can accommodate:
package com.titan.cabin;

import java.rmi.RemoteException;

public interface CabinRemote extends javax.ejb.EJBObject {
    public String getName() throws RemoteException;
    public void setName(String str) throws RemoteException;
    public int getDeckLevel() throws RemoteException;
    public void setDeckLevel(int level) throws RemoteException;
    public int getShipId() throws RemoteException;
    public void setShipId(int sp) throws RemoteException;
    public int getBedCount() throws RemoteException;
    public void setBedCount(int bc) throws RemoteException; 
}
The CabinRemote interface defines four properties: the name, deckLevel, shipId, and bedCount. Properties are attributes of an enterprise bean that can be accessed by public set and get methods. The methods that access these properties are not explicitly defined in the CabinRemote interface, but the interface clearly specifies that these attributes are readable and changeable by a client.
Notice that we have made the CabinRemote interface a part of a new package named com.titan.cabin. Place all the classes and interfaces associated with each type of bean in a package specific to the bean. Because our beans are for the use of the Titan cruise line, we placed these packages in the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing a Session Bean
Session beans act as agents to the client, controlling workflow (the business process) and filling the gaps between the representation of data by entity beans and the business logic that interacts with that data. Session beans are often used to manage interactions between entity beans and can perform complex manipulations of beans to accomplish certain tasks. Since we have defined only one entity bean so far, we will focus on a complex manipulation of the Cabin EJB rather than the interactions of the Cabin EJB with other entity beans. The interactions of entity beans within session beans will be explored in greater detail in Chapter 12.
Client applications and other beans use the Cabin EJB in a variety of ways. Some of these uses were predictable when the Cabin EJB was defined, but many were not. After all, an entity bean represents data—in this case, data describing a cabin. The uses to which we put that data will change over time—hence the importance of separating the data itself from the workflow. In Titan's business system, for example, we may need to list and report on cabins in ways that were not predictable when the Cabin EJB was defined. Rather than change the Cabin EJB every time we need to look at it differently, we will obtain the information we need using a session bean. Changing the definition of an entity bean should be done only within the context of a larger process—for example, a major redesign of the business system.
In Chapter 1 and Chapter 2, we talked hypothetically about a TravelAgent EJB that was responsible for the workflow of booking a passage on a cruise. This session bean will be used in client applications accessed by travel agents throughout the world. In addition to booking tickets, the TravelAgent EJB provides information about which cabins are available on the cruise. In this chapter, we will develop the first implementation of this listing behavior in the TravelAgent EJB. The listing method we develop in this example is admittedly very crude and far from optimal. However, this example is useful for demonstrating how to develop a very simple stateless session bean and how these session beans can manage other beans. In Chapter 12, we will rewrite the listing method. The "list cabins" behavior developed here will be used by travel agents to provide customers with a list of cabins that can accommodate their needs. The Cabin EJB does not directly support this kind of list, nor should it. The list we need is specific to the TravelAgent EJB, so it's the TravelAgent EJB's responsibility to query the Cabin EJB and produce the list.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: The Client View
Developing the Cabin EJB and the TravelAgent EJB should have raised your confidence, but it also should have raised a lot of questions. So far, we have glossed over most of the details involved in developing, deploying, and accessing these enterprise beans. In this chapter and the ones that follow, we will slowly peel away the layers of the Enterprise JavaBeans onion to expose the details of EJB application development.
This chapter focuses specifically on the client's view of entity and session beans. Message-driven beans are not covered in this chapter—they are covered in detail in Chapter 13. The client, whether it is an application or another enterprise bean, doesn't work directly with the beans in the EJB system. Instead, clients interact with a set of interfaces that provide access to beans and their business logic. These interfaces consist of the JNDI API and an EJB client-side API. JNDI allows us to find and access enterprise beans regardless of their location on the network; the EJB client-side API is the set of interfaces and classes developers use on the client to interact with enterprise beans.
The best approach to this chapter is to read about several features of the client view and then follow the workbook examples to see those features in action. This will provide you with hands-on experience and a much clearer understanding of the concepts. Have fun, experiment, and you'll be sure to understand the fundamentals.
In Chapter 4, the client application started by creating an InitialContext, which it then used to get a remote reference to the homes of the Cabin and TravelAgent EJBs. The InitialContext is part of a larger API called the Java Naming and Directory Interface ( JNDI). We use JNDI to look up an EJB home in an EJB server just like you might use a phone book to find the home number of a friend or business associate.
JNDI is a standard Java optional package that provides a uniform API for accessing a wide range of services. In this respect, it is somewhat similar to JDBC, which provides uniform access to different relational databases. Just as JDBC lets you write code that doesn't care whether it's talking to an Oracle database or a Sybase database, JNDI lets you write code that can access different directory and naming services, such as LDAP, Novell NetWare NDS, Sun Solaris NIS+, CORBA Naming Service, and the naming services provided by EJB servers. EJB servers are required to support JNDI by organizing beans into a directory structure and providing a JNDI driver, called a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Locating Beans with JNDI
In Chapter 4, the client application started by creating an InitialContext, which it then used to get a remote reference to the homes of the Cabin and TravelAgent EJBs. The InitialContext is part of a larger API called the Java Naming and Directory Interface ( JNDI). We use JNDI to look up an EJB home in an EJB server just like you might use a phone book to find the home number of a friend or business associate.
JNDI is a standard Java optional package that provides a uniform API for accessing a wide range of services. In this respect, it is somewhat similar to JDBC, which provides uniform access to different relational databases. Just as JDBC lets you write code that doesn't care whether it's talking to an Oracle database or a Sybase database, JNDI lets you write code that can access different directory and naming services, such as LDAP, Novell NetWare NDS, Sun Solaris NIS+, CORBA Naming Service, and the naming services provided by EJB servers. EJB servers are required to support JNDI by organizing beans into a directory structure and providing a JNDI driver, called a service provider, for accessing that directory structure. Using JNDI, an enterprise can organize its beans, services, data, and other resources in a large virtual-directory structure, which can provide a powerful mechanism for binding together disparate systems.
Two of JNDI's greatest features are that it is virtual and dynamic. JNDI is virtual because it allows one directory service to be linked to another through simple URLs. The URLs in JNDI are analogous to HTML links. Clicking on a link in HTML allows a user to load the contents of a web page. The new web page can be downloaded from the same host as the starting page or from a completely different web site—the location of the linked page is transparent to the user. Likewise, using JNDI, you can drill down through directories to files, printers, EJB home objects, and other resources using links that are similar to HTML links. The directories and subdirectories can be located in the same host or can be physically hosted at different locations. The user doesn't know or care where the directories are actually located. As a developer or administrator, you can create virtual directories that span a variety of services over many different physical locations.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Remote Client API
Enterprise bean developers are required to provide a bean class, component interfaces, and, for entity beans, a primary key. Only the component interfaces and primary key class are visible to the client; the bean class is not. The component interfaces and primary key contribute to the client-side API in EJB.
In EJB 1.1, all clients, whether they are in the same container system or not, must use the Remote Client API, which means they must use the remote interface, the remote home interface, and Java RMI in all their interactions. In EJB 2.0, remote clients still must use the Remote Client API, but enterprise beans that are located in the same EJB container system have the option of using the Local Client API. The Local Client API provides local component interfaces and avoids the restrictions and overhead of the Remote Client API.
This section examines in more detail the remote component interfaces and the primary key, as well as other Java types that make up EJB's remote client-side API, which is used in both EJB 2.0 and EJB 1.1. This will provide you with a better understanding of how the remote client-side API is used and its relationship with the bean class on the EJB server. At the end of this chapter, in Section 5.3, we will examine the use of local component interfaces for EJB 2.0 readers.
Enterprise JavaBeans 2.0 and 1.1 define an enterprise bean's remote interfaces in terms of Java RMI-IIOP, which enforces compliance with CORBA. This means that the underlying protocol used by remote clients to access enterprise beans can be anything the vendor wants as long as it supports the types of interfaces and arguments that are compatible with Java RMI-IIOP. EJB 1.1 required only that the wire protocol used by vendors utilize types that were compatible with Java RMI-IIOP. In other words, the interface types and values used in remote references had to be compliant with the types allowed for Java RMI-IIOP. This ensured that early Java RMI-IIOP adopters were supported and made for a seamless transition for other vendors who wanted to use real Java RMI-IIOP in EJB 2.0. In EJB 2.0, vendors can still offer other Java RMI-IIOP-compatible protocols, but in addition to any proprietary protocols they support, they must also support the CORBA IIOP 1.2 protocol as defined in the CORBA 2.3.1 specification.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
EJB 2.0: The Local Client API
EJB 2.0 introduces the concept of local component interfaces, which are intended to provide different semantics and a different execution context for enterprise beans that work together within the same EJB container system.
When two or more enterprise beans interact, they are usually co-located; that is, they are deployed in the same EJB container system and execute within the same Java Virtual Machine. Co-located beans do not need to use the network to communicate. Since they are in the same JVM, they can communicate more directly by avoiding the overhead of Java RMI-IIOP. However, the EJB 1.1 specification required that even co-located beans utilize Java RMI-IIOP semantics for communication. This specification did not require that a network protocol be used, but it did require that Java RMI-IIOP types be used and that all objects be copied, rather then referenced, when passed as arguments to methods.
EJB 1.1 vendors, determined to squeeze every ounce of performance out of their servers, optimized co-located beans. The optimizations required that the EJB container interpose on invocations from one EJB to another but allowed vendors to avoid the overhead of the network; arguments and returned values were processed within the JVM by the container and not serialized over the network. However, arguments still had to be copied, rather then passed by reference, which slowed invocations down slightly. Many, if not most, vendors offered a proprietary switch that allowed deployers to turn off the copy semantics of co-located beans, so that objects passed from one enterprise bean to another in the same container system could be passed by reference rather then copied, which improved performance.
Optimizations of co-located beans that included switches for toggling argument copying eventually became so pervasive across vendors that Sun Microsystems decided to make this option part of the specification. This is why local component interfaces, which make up the Local Client API, were introduced.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: EJB 2.0 CMP: Basic Persistence
In Chapter 4, we started developing some simple enterprise beans, skipping over a lot of the details about developing enterprise beans. In this chapter, we'll take a thorough look at the process of developing entity beans. Entity beans model business concepts that can be expressed as nouns. This is a rule of thumb rather than a requirement, but it helps in determining when a business concept is a candidate for implementation as an entity bean. In grammar school, you learned that nouns are words that describe a person, place, or thing. The concepts of "person" and "place" are fairly obvious: a person EJB might represent a customer or passenger, and a place EJB might represent a city or port-of-call. Similarly, entity beans often represent "things": real-world objects like ships, credit cards, and so on. An entity bean can even represent a fairly abstract thing, such as a reservation. Entity beans describe both the state and behavior of real-world objects and allow developers to encapsulate the data and business rules associated with specific concepts; a Customer EJB encapsulates the data and business rules associated with a customer, for example. This makes it possible for data associated with a concept to be manipulated consistently and safely.
In Titan's cruise ship business, we can identify hundreds of business concepts that are nouns and, therefore, could conceivably be modeled by entity beans. We've already seen a simple Cabin EJB in Chapter 4, and we'll develop Customer and Address EJBs in this chapter. Titan could clearly make use of a Cruise EJB, a Reservation EJB, and many others. Each of these business concepts represents data that needs to be tracked and possibly manipulated.
Entities represent data in the database, so changes to an entity bean result in changes to the database. There are many advantages to using entity beans instead of accessing the database directly. Utilizing entity beans to objectify data provides programmers with a simpler mechanism for accessing and changing data. It is much easier, for example, to change a customer's name by calling
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Overview
In Chapter 4, we started developing some simple enterprise beans, skipping over a lot of the details about developing enterprise beans. In this chapter, we'll take a thorough look at the process of developing entity beans. Entity beans model business concepts that can be expressed as nouns. This is a rule of thumb rather than a requirement, but it helps in determining when a business concept is a candidate for implementation as an entity bean. In grammar school, you learned that nouns are words that describe a person, place, or thing. The concepts of "person" and "place" are fairly obvious: a person EJB might represent a customer or passenger, and a place EJB might represent a city or port-of-call. Similarly, entity beans often represent "things": real-world objects like ships, credit cards, and so on. An entity bean can even represent a fairly abstract thing, such as a reservation. Entity beans describe both the state and behavior of real-world objects and allow developers to encapsulate the data and business rules associated with specific concepts; a Customer EJB encapsulates the data and business rules associated with a customer, for example. This makes it possible for data associated with a concept to be manipulated consistently and safely.
In Titan's cruise ship business, we can identify hundreds of business concepts that are nouns and, therefore, could conceivably be modeled by entity beans. We've already seen a simple Cabin EJB in Chapter 4, and we'll develop Customer and Address EJBs in this chapter. Titan could clearly make use of a Cruise EJB, a Reservation EJB, and many others. Each of these business concepts represents data that needs to be tracked and possibly manipulated.
Entities represent data in the database, so changes to an entity bean result in changes to the database. There are many advantages to using entity beans instead of accessing the database directly. Utilizing entity beans to objectify data provides programmers with a simpler mechanism for accessing and changing data. It is much easier, for example, to change a customer's name by calling
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Customer EJB
Content preview·