Book Home Enterprise JavaBeans Search this book

2.2. Using Enterprise Beans

Now that you actually have a bean to work with, let's look at how a client would work with a bean to do something useful. We'll start with the Cabin bean that was defined earlier. A cabin is a thing or place whose description is stored in a database. To make the example a little bit more real, imagine that there are other entity beans, including a Ship, Cruise, Ticket, Passenger, Employee, and so on.

2.2.1. Getting Information from an Entity Bean

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:

CruiseHome cruiseHome = ... getCruiseHome();
// Get the cruise id from a text field.
String cruiseID = textFields1.getText();
// Create an EJB primary key from the cruise id.
CruisePrimaryKey pk = new CruisePrimaryKey(cruiseID);
// Use the primary key to find the cruise.
Cruise 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.
Ship ship = cruise.getShip();
// Set text field 3 to show the ship's name.
textField3.setText(ship.getName());

// Get a list of all the cabins on the ship as remote references
// to the cabin beans.
Cabin [] cabins = ship.getCabins();

// Iterate through the enumeration, adding the name of each cabin
// to a list box.
for (int i = 0; i < cabins.length; i++){
    Cabin cabin = cabins[i];
    listBox1.addItem(cabin.getName());
}

Let's start by getting a remote reference to the EJB home for an entity bean that represents a cruise. It's not shown in the example, but references to the EJB home are obtained using JNDI. Java Naming and Directory Interface ( 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 rest assured that it will be covered in subsequent chapters.

We read a cruise ID from a text field, use it to create a primary key, and use that primary key together with the EJB home to get a Cruise, the object that implements the business methods of our bean. Once we have the appropriate cruise, we can ask the cruise to give us the Ship that will be used for the cruise. We can then get a list of Cabins from the Ship and display the names of the Cabins in the client.

Entity beans model data and behavior. They provide a system with a reusable and consistent interface to data in the database. The behavior used in entity beans is usually focused on applying business rules that pertain directly to changing data. In addition, entity beans can model relationships with other entities. A ship, for example, has many cabins. We can get a list of cabins owned by the ship by invoking the ship.getCabins() method.

Entity beans are shared by many clients. An example is the Ship bean. The behavior and data associated with a Ship bean will be used concurrently by many clients on the system. There are only three ships in Titan's fleet, so it's easy to imagine that several clients will need to access these entities at the same time. Entity beans are designed to service multiple clients, providing fast, reliable access to data and behavior while protecting the integrity of data changes. Because entity beans are shared, we can rest assured that everyone is using the same entity and seeing the same data as it changes. In other words, we don't have duplicate entities with different representations of the same data.[1]

[1] This is dependent on the isolation level set on the bean's data, which is discussed in more detail in Chapter 8, "Transactions".

2.2.2. Modeling Workflow with Session Beans

Entity beans are useful for objectifying data and describing business concepts that can be expressed as nouns, but they're not very good at representing a process or a task. A Ship bean provides methods and behavior for doing things directly to a ship, but it does not define the context under which these actions are taken. The previous example retrieved data about cruises and ships; we could also have modified this data. And if we had gone to enough effort, we could have figured out how to book a passenger--perhaps by adding a Customer bean to a Cruise bean or adding a customer to a list of passengers maintained by the ship. We could try to shove methods for accepting payment and other tasks related to booking into our client application, or even into the Ship or Cabin beans, but that's a contrived and inappropriate solution. We don't want business logic in the client application--that's why we went to a multitier architecture in the first place. Similarly, we don't want this kind of logic in our entity beans that represent ships and cabins. Booking passengers on a ship or scheduling a ship for a cruise are the types of activities or functions of the business, not the Ship or the Cabin bean, and are therefore expressed in terms of a process or task.

Session beans act as agents for the client managing business processes or tasks; they're the appropriate place for business logic. A session bean is not persistent like an entity bean; nothing in a session bean maps directly into a database or is stored between sessions. Session beans work with entity beans, data, and other resources to control workflow. Workflow is the essence of any business system because it expresses how entities interact to model the actual business. Session beans control tasks and resources but do not themselves represent data.

The following code demonstrates how a session bean, designed to make cruise line reservations, might control the workflow of other entity and session beans to accomplish this task. Imagine that a piece of client software, in this case a user interface, obtains a remote reference to a TravelAgent session bean. Using the information entered into text fields by the user, the client application books a passenger on a cruise:

// Get the credit card number from the text field.
String creditCard = textField1.getText();
int cabinID = Integer.parseInt(textField2.getText());
int cruiseID = Integer.parseInt(textField3.getText());

// Create a new Reservation session passing in a reference to a 
// customer entity bean.
TravelAgent travelAgent = TravelAgentHome.create(customer);

// Set cabin and cruise IDs.
travelAgent.setCabinID(cabinID);
travelAgent.setCruiseID(cruiseID);

// Using the card number and price, book passage.
// This method returns a Ticket object.
Ticket ticket = travelAgent.bookPassage(creditCard, price);

This is a fairly coarse-grained abstraction of the process of booking a passenger on a cruise. Coarse-grained means that most of the details of the booking process are hidden from the client. Hiding the fine-grained details of workflow is important because it provides us with more flexibility in how the system evolves and how clients are allowed to interact with the EJB system.

The following listing shows some of the code included in the TravelAgentBean. The bookPassage() method actually works with three entity beans, the Customer, Cabin, and Cruise beans, and another session bean, the ProcessPayment bean. The ProcessPayment bean provides several different methods for making a payment including check, cash, and credit card. In this case, we are using the ProcessPayment session to make a credit card purchase of a cruise ticket. Once payment has been made, a serializable Ticket object is created and returned to the client application.

public class TravelAgentBean implements javax.ejb.SessionBean {

    public Customer customer;
    public Cruise cruise;
    public Cabin cabin;

    public void ejbCreate(Customer cust) {
        customer = cust;
    }
    public Ticket bookPassage(CreditCard card, double price)
        throws IncompleteConversationalState {
        // EJB 1.0: also throws RemoteException

        if (customer == null || cruise == null || cabin == null) {
            throw new IncompleteConversationalState();
        }
        try {
            ReservationHome resHome = (ReservationHome)
                getHome("ReservationHome",ReservationHome.class);
            Reservation reservation =
            resHome.create(customer, cruise, cabin,price);
            ProcessPaymentHome ppHome = (ProcessPaymentHome)
                getHome("ProcessPaymentHome",ProcessPaymentHome.class);
            ProcessPayment process = ppHome.create();
            process.byCredit(customer, card, price);

            Ticket ticket = new Ticket(customer,cruise,cabin,price);
            return ticket;
        } catch(Exception e){
            // EJB 1.0: throw new RemoteException("",e);
            throw new EJBException(e);
        }
    }

// More business methods and EJB state management methods follow.
}

This example leaves out some details, but it demonstrates the difference in purpose between a session bean and an entity bean. Entity beans represent the behavior and data of a business object, while session beans model the workflow of beans. The client application uses the TravelAgent bean to perform a task using other beans. For example, the TravelAgent bean uses a ProcessPayment bean and a Reservation bean in the process of booking a passage. The ProcessPayment bean processes a credit card and the Reservation bean records the actual reservation in the system. Session beans can also be used to read, update, and delete data that can't be adequately captured in an entity bean. Session beans don't represent records or data in the database like entity beans but can access data in the database.

All the work performed by TravelAgent session bean could have been coded in the client application. Having the client interact directly with entity beans is a common but troublesome design approach because it ties the client directly to the details of the business tasks. This is troublesome for two reasons: any change in the entity beans and their interaction require changes to the client, and it's very difficult to reuse the code that models the workflow.

Session beans are coarse-grained components that allow clients to perform tasks without being concerned with the details that make up the task. This allows developers to update the session bean, possibly changing the workflow, without impacting the client code. In addition, if the session bean is properly defined, other clients that perform the same tasks can reuse it. The ProcessPayment session bean, for example, can be reused in many other areas besides reservations, including retail and wholesale sales. For example, the ship's gift shop could use the ProcessPayment bean to process purchases. As a client of the ProcessPayment bean, the TravelAgent bean doesn't care how ProcessPayment works; it's only interested in the ProcessPayment bean's coarse-grained interface, which validates and records charges.

Moving workflow logic into a session bean also helps to thin down the client applications and reduce network traffic and connections. Excessive network traffic is actually one of the biggest problems in distributed object systems. Excessive traffic can overwhelm the server and clog the network, hurting response times and performance. Session beans, if used properly, can substantially reduce network traffic by limiting the number of requests needed to perform a task. In distributed objects, every method invocation produces network traffic. Distributed objects communicate requests using an RMI loop. This requires that data be streamed between the stub and skeleton with every method invocation. With session beans, the interaction of beans in a workflow is kept on the server. One method invocation on the client application results in many method invocations on the server, but the network only sees the traffic produced by one method call on the session bean. In the TravelAgent bean, the client invokes bookPassage(), but on the server, the bookPassage() method produces several method invocations on the home interface and remote interface of other beans. For the network cost of one method invocation, the client gets several method invocations.

In addition, session beans reduce the number of network connections needed by the client. The cost of maintaining many network connections can be very high, so reducing the number of connections that each client needs is important in improving the performance of the system as a whole. When session beans are used to manage workflow, the number of connections that each client has to the server is substantially reduced, which improves the EJB server's performance. Figure 2-3 compares the network traffic and connections used by a client that only uses entity beans to that used by a client that uses session beans.

figure

Figure 2-3. Session beans reduce network traffic and thin down clients

Session beans also limit the number of stubs used on the client, which saves the client memory and processing cycles. This may not seem like a big deal, but without the use of session beans, a client might be expected to manage hundreds or even thousands of remote references at one time. In the TravelAgent bean, for example, the bookPassage() method works with several remote references, but the client is only exposed to the remote reference of the TravelAgent bean.

2.2.2.1. Stateless and stateful session beans

Session beans can be either stateful or stateless. Stateful session beans maintain conversational state when used by a client. Conversational state is not written to a database; it's state that is kept in memory while a client uses a session. Maintaining conversational state allows a client to carry on a conversation with a bean. As each method on the bean is invoked, the state of the session bean may change, and that change can affect subsequent method calls. The TravelAgent session bean, for example, may have many more methods than the bookPassage() method. The methods that set the cabin and cruise IDs are examples. These set methods are responsible for modifying conversational state. They convert the IDs into remote references to Cabin and Cruise beans that are later used in the bookPassage() method. Conversational state is only kept for as long as the client application is actively using the bean. Once the client shuts down or releases the TravelAgent bean, the conversational state is lost forever. Stateful session beans are not shared among clients; they are dedicated to the same client for the life of the bean.

Stateless session beans do not maintain any conversational state. Each method is completely independent and uses only data passed in its parameters. The ProcessPayment bean is a perfect example of a stateless session bean. The ProcessPayment bean doesn't need to maintain any conversational state from one method invocation to the next. All the information needed to make a payment is passed into the byCreditCard() method. Stateless session beans provide the highest performance in terms of throughput and resource consumption of all the bean types because few stateless session bean instances are needed to serve hundreds, possibly thousands of clients. Chapter 7, "Session Beans" talks more about the use of stateless session beans.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.

This HTML Help has been published using the chm2web software.