Enterprise JavaBeans - Part 3

Gopalan Suresh Raj

EJB Components

In an earlier section, you saw the basic EJB model. Now, you have a more in-depth look at some of the major components of the EJB architecture, shown in Figure 4, so you can understand their run-time behavior.

Figure 4: Major components of the EJB architecture

The Home Interface and the Home Object

When an EJB client needs to use the services of an enterprise bean, it creates the EJB through its home interface. The client specifically uses one of the multiple create() methods the home interface defines. The implementation of the home interface is done through an object called the home object. An instance of this home object is created within the server and is made available to the clients as a factory for creating the enterprise bean.

Finding the Home Object

The EJB client locates the home object through JNDI because a reference to the home object is placed in the naming service. The location of the namespace and the JNDI context factory class name are provided to the client initially. In addition to providing the location and class name, the client should also have some knowledge of how to locate the home object within the naming tree.

When an EJB deployer deploys an EJB onto an EJB server, he or she specifies a particular location in the naming tree such as "cup/chap8/Account". Then, the EJB client must be given this fully qualified pathname to locate and obtain a reference to the "Account" home object.

The code segment the client uses to create the bean through the home object looks something like Listing 1:

// get the JNDI naming context
Context initialCtx = new InitialContext ();
// use the context to lookup the EJB Home interface
AccountHome home =(AccountHome)initialCtx.lookup ("com/~gopalan/Account");
// use the Home Interface to create a Session bean object
Account account = home.create (1234, "Athul", 1000671.54d);

Listing 1: Client code to create an EJB

Definition of the Home Interface

The home object is an implementation of an interface that extends the javax.ejb.EJBHome interface. It has the needed create(), find(), and remove() methods, each of these is matched with a corresponding ejbCreate(), ejbFind(), and ejbRemove() method of the same signature in the actual enterprise Bean implementation being created. Methods also exist to obtain the metadata of the enterprise Bean. The EJBHome interface is defined in the specification as shown in Listing 2:

public interface javax.ejb.EJBHome extends Remote {
 public abstract void remove (Handle handle) 
  throws RemoteException, RemoveException;
 public abstract void remove (Object primaryKey) 
  throws RemoteException,RemoveException;
 public abstract EJBMetaData getEJBMetaData () 
  throws RemoteException;
}

Listing 2: The EJBHome interface definition

The EJB developer has to define ejbCreate() methods in his enterprise beans. The EJB developer is also required to define corresponding create() methods that match the signatures in the EJB’s home interface. If the developer is coding an entity bean, she or he may have to define finder methods in the home interface, which allows clients to locate existing entity beans based on their identity.

A typical home interface definition for an EJB may look something like Listing 3:

import javax.ejb.*;
import java.rmi.*;

public interface AccountHome extends EJBHome {
 
 Account create(int accountNo, String customer)
  throws CreateException, RemoteException;
 
 Account create(int accountNo, String customer, double startingBalance)
  throws CreateException, RemoteException;
 
 Account findByPrimaryKey(AccountPK accountNo)
  throws FinderException, RemoteException;
}

Listing 3: The AccountHome interface definition

The Remote Interface

The EJB developer must create a remote interface, which describes the business methods of the bean the EJB client would be able to invoke. The EJBObject will have the implementation code generated by the container tools for this interface.

The method names and the signatures listed in the remote interface must exactly match the method names and signatures of the business methods defined by the enterprise bean. This differs from the home interface, whose method signatures matched, but whose names were different.

A typical remote interface definition for an EJB may look like Listing 4.

import javax.ejb.*;
import java.rmi.*;

public interface Account extends EJBObject {
 
 void credit (double amount) throws RemoteException;
 void debit (double amount) throws RemoteException;
 double getBalance () throws RemoteException;
}

Listing 4: The Account Remote interface definition

The EJBObject

The EJBObject is a network-visible object with a stub and skeleton that acts as a proxy for the enterprise bean. The bean’s remote interface extends the javax.ejb.EJBObject interface, making the EJBObject class specific to the bean class. For each enterprise bean, a custom EJBObject class exists.

Entity and Session Beans

Enterprise beans are building blocks that can be used alone or with other enterprise beans to build complete, robust, thin-client multitiered applications. An EJB is a body of code with fields and methods to implement modules of business logic. They can either be transient or persistent. Two types of enterprise beans can exist:

Figure 5 illustrates a high-level view of an EJB environment with session and entity enterprise beans.

Figure 5: A typical EJB environment with entity and session beans

Before beginning a discussion of entity and session beans, you must understand the concept of passivation and activation. Passivation is the process by which the state of a bean is saved to persistent storage and then is swapped out. Activation is the process by which the state of a bean is restored by swapping it in from persistent storage.

Entity Beans

An entity bean represents persistent data maintained in a domain model, as well as methods that act on that data. To be more specific, an entity bean maps to a record in your domain model. In a relational database context, one bean exists for each row in a table. This is not a new concept; this is how object databases have been modeled all along. A primary key identifies each entity bean. Entity beans are created by using an object factory create() method. Entity beans are also implicitly persistent, as an EJB object can manage its own persistence or delegate its persistence to its container.

Entity beans always have states, which can be persisted and stored across multiple invocations. Multiple EJB clients may, however, share an entity bean. The lifetime of an entity bean is not limited by the lifetime of the virtual machine within which it executes. A crash of the virtual machine may result in a rollback of the current transaction, but will neither destroy the entity bean nor invalidate the references that other clients have to this entity bean. Moreover, a client can later connect to the same entity bean using its object reference because it encapsulates a unique primary key allowing the enterprise bean or its container to reload its state. Entity beans can thus survive system shutdowns.

Persistence in entity beans is of two types:

Container-managed persistence: Here, the EJB container is responsible for saving the state of the entity bean. Because it is container-managed, the implementation is independent of the data source. All container-managed fields need to be specified in the deployment descriptor, however, for the persistence to be automatically handled by the container.

Bean-managed persistence: Here, the entity bean is directly responsible for saving its own state and the container does not need to generate any database calls. Consequently, this implementation is less adaptable than the previous one as the persistence needs to be hard-coded into the bean.

To summarize, every entity bean has the following characteristics:

Session Beans

A session bean is created by a client and, in most cases, exists only for the duration of a single session. It performs operations on behalf of the client, such as database access or number crunching based on some formula. Although session beans can be transactional, they are not recoverable following a system crash. They can be stateless or they can maintain conversational state across methods and transactions. The container manages the conversational state of a session bean if it needs to be evicted from memory. A session bean must manage its own persistent data.

Each session bean is usually associated with one EJB client, which is responsible for creating and destroying it. Thus, session beans are transient and will not outlive the virtual machine on which they were created. A session bean can either maintain its state or be stateless. Session beans, however, do not survive a system shutdown.

Two types of session beans exist:

Stateless session beans: These types of session EJBs have no internal state. Because they are stateless, they needn’t be passivated and can be pooled to service multiple clients.

Stateful session beans: These types of session beans possess internal states, hence, they need to handle activation and passivation. Because they can be persisted, they are also called persistent session beans. Only one EJB Client can exist per stateful session bean, however. Stateful session beans can be saved and restored across client sessions. The getHandle() method returns a bean object’s instance handle, which can be used to save the bean’s state. Later, to restore a bean from persistent storage, the getEJBObject() method can be invoked.

The characteristics of a session bean can be summarized as follows:

Every session bean can read and update a database on behalf of the client. Its fields may contain conversational state on behalf of the client. The state describes the conversation represented by a specific client/instance pair. Within a transaction, some of this data may be cached in the bean.

Session beans are supposed to be private resources, used only by the client that created it. For this reason, a session bean hides its identity and is anonymous, in sharp contrast to an entity bean that exposes its identity through its primary key.

Table 2 summarizes some of the major differences between a session bean and an entity bean.

Session Bean Entity Bean
The data members of the session bean contain conversational state. The data members of the entity bean represent actual data in the domain model.
A session bean may handle database access for a single client. Entity beans share database access for multiple clients.
Because session beans are about a conversation with a single client, session beans are allowed to store per-client state information.. Because entity beans are shared between multiple clients, they do not allow storage of per-client state information.
The relationship between a session bean and its client is one-to-one. The relationship between an entity bean and a row in the domain model is one-to-one.
The life of the session bean is limited to the life of its client. An entity bean persists as long as the data exists in the database.
Session beans can be transaction aware. Entity beans are transactional.
Session beans do not survive server crashes. Entity beans survive server crashes.

Table 2: Differences Between a Session Bean and an Entity Bean

Go to Part 4 of this article

You can always refer to my Homepage at http://www.execpc.com/~gopalan for more EJB source code. Another good resource is the EJB-INTEREST@JAVA.SUN.COM mailing list from Sun and the EJBHome mailing list ejbhome-discuss@iona.com from Iona.

click here to go to
My EJB HomePage...

 

About the Author...
Gopalan Suresh Raj is a Software Architect, Developer and an active Author. He is contributing author to a couple of books "Enterprise Java Computing-Applications and Architecture" and "The Awesome Power of JavaBeans". His expertise spans enterprise component architectures and distributed object computing. Visit him at his Web Cornucopia© site (http://www.execpc.com/~gopalan) or mail him at gopalan@execpc.com.

Go to the Component Engineering Cornucopia page

This site was developed and is maintained by Gopalan Suresh Raj

This page has been visited times since September 21,1998.

Last Updated : Dec 19, '98

If you have any questions, comments, or problems regarding this site, please write to me I would love to hear from you.


Copyright (c) 1997-2000, Gopalan Suresh Raj - All rights reserved. Terms of use.

All products and companies mentioned at this site are trademarks of their respective owners.