Gopalan Suresh Raj's Web Cornucopia
An Oasis for the parched Enterprise Services Engineer/Developer

    Container Managed Models-Enterprise JavaBeans - Part 3


    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

    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:

    • Entity beans—These beans are generally used to model a business entity.
    • Session beans—These are more general purpose server-side beans.

    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

    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:

    • Entity beans can share access from multiple users.
    • Entity beans can participate in transactions.
    • Entity beans represent data in a domain model.
    • Entity beans are persistent. They live as long as the data lives in the domain model.
    • Entity beans can survive EJB server crashes. Any EJB server crash is always transparent to the client.
    • Entity beans have a persistent object reference. The object reference encapsulates the persistent key for this bean.

    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:

    • Session EJBs execute on behalf of a single client. A session bean instance is an extension of the client that creates it.
    • Session beans may be transaction-aware.
    • Session beans can update data in an underlying database.
    • Session beans are relatively short-lived. The lifetime of stateless session beans is limited to that of their client.
    • Session beans may be destroyed when the EJB server crashes. The client has to establish connection with a new session bean object to resume any computation.
    • Session beans do not represent data that must be stored in a database.
    • 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.

    Author Bibliography

    Gopalan Suresh Raj is a Senior Analyst, Software Architect, and Developer with expertise in multi-tiered systems development, enterprise service architectures, and distributed computing. He is also an active author, including contributions to Professional JMS Programming, Wrox Press, 2001, Enterprise Java Computing-Applications and Architecture, Cambridge University Press, 1999, and The Awesome Power of JavaBeans, Manning Publications Co., 1998. He has submitted papers at international fora, and his work has been published in numerous technical journals. Visit him at his Web Cornucopia© site ( or mail him at