Skip Headers

Oracle® Application Server Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 2 (10.1.2)
Part No. B15505-01
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

Which Type of EJB Should You Use in Your Application?

Enterprise JavaBeans (EJBs) can be one of three types: session beans, entity beans, or message-driven beans.

Each EJB type is described in the sections below:

What is a Session Bean?

A session bean implements one or more business tasks. A session bean might contain methods that query and update data in a relational table. Session beans are often used to implement services. For example, an application developer might implement one or several session beans that retrieve and update inventory data in a database.

Session beans are transient because they do not survive a server crash or a network failure. If, after a crash, you instantiate a bean that had previously existed, the state of the previous instance is not restored. State can be restored only to entity beans.

A session bean implements the javax.ejb.SessionBean interface, which has the following definition:

public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean {
   public abstract void ejbActivate(); 
   public abstract void ejbPassivate();
   public abstract void ejbRemove();
   public abstract void setSessionContext(SessionContext ctx);
}

At a minimum, the session bean must implement the following methods, as specified in the javax.ejb.SessionBean interface:

EJB Method Description
ejbCreate() The container invokes this method right before it creates the bean. Stateless session beans must do nothing in this method. Stateful session beans can initiate state in this method.
ejbActivate() The container invokes this method right after it reactivates the bean.
ejbPassivate() The container invokes this method right before it passivates the bean. You can turn off passivation for stateful session beans.
ejbRemove() A container invokes this method before it ends the life of the session object. This method performs any required clean-up—for example, closing external resources such as file handles.
setSessionContext (SessionContext ctx) This method associates a bean instance with its context information. The container calls this method after the bean creation. The enterprise bean can store the reference to the context object in an instance variable, for use in transaction management. Beans that manage their own transactions can use the session context to get the transaction context.

For more information on how to develop session beans, see Chapter 3, "Implementing Session Beans".

Retrieving the Context Using setSessionContext

You use this method to obtain a reference to the context of the bean. Session beans have session contexts that the container maintains and makes available to the beans. The bean may use the methods in the session context to make callback requests to the container.

The container invokes setSessionContext method, after it first instantiates the bean, to enable the bean to retrieve the session context. The container will never call this method from within a transaction context. If the bean does not save the session context at this point, the bean will never gain access to the session context.

When the container calls this method, it passes the reference of the SessionContext object to the bean. The bean can then store the reference for later use. The following example shows the bean saving the session context in the sessctx variable.

import javax.ejb.*;
import oracle.oas.ejb.*;

public class myBean implements SessionBean {
   SessionContext sessctx;

   void setSessionContext(SessionContext ctx) {
      sessctx = ctx;   // session context is stored in 
                       // instance variable
   }
   // other methods in the bean
}

The javax.ejb.SessionContext interface has the following definition:

public interface SessionContext extends javax.ejb.EJBContext {
    public abstract EJBObject getEJBObject();
}

And the javax.ejb.EJBContext interface has the following definition:

public interface EJBContext {
    public EJBHome         getEJBHome(); 
    public Properties      getEnvironment();
    public Principal       getCallerPrincipal();
    public boolean         isCallerInRole(String roleName);
    public UserTransaction getUserTransaction();
    public boolean         getRollbackOnly();
    public void            setRollbackOnly();
}

A bean needs the session context when it wants to perform the operations listed in Table 1-1.

Table 1-1 SessionContext Operations

Method Description
getEnvironment() Get the values of properties for the bean.
getUserTransaction() Get a transaction context, which allows you to demarcate transactions programmatically. This is valid only for beans that have been designated transactional.
setRollbackOnly() Set the current transaction so that it cannot be committed.
getRollbackOnly() Check whether the current transaction has been marked for rollback only.
getEJBHome() Retrieve the object reference to the corresponding EJBHome (home interface) of the bean.

There are two types of session beans:

  • What is a Stateless Session Bean?—Stateless session beans do not share state or identity between method invocations. They are useful mainly in middle-tier application servers that provide a pool of beans to process frequent and brief requests.

  • What is a Stateful Session Bean?—Stateful session beans are useful for conversational sessions, in which it is necessary to maintain state, such as instance variable values or transactional state, between method invocations. These session beans are mapped to a single client for the life of that client.

For more information on how to develop session beans, see Chapter 3, "Implementing Session Beans".

What is a Stateless Session Bean?

A stateless session bean does not maintain any state for the client. It is strictly a single invocation bean. It is employed for reusable business services that are not connected to any specific client, such as generic currency calculations, mortgage rate calculations, and so on. Stateless session beans may contain client-independent, read-only state across a call. Subsequent calls are handled by other stateless session beans in the pool. The information is used only for the single invocation.

The EJB container maintains a pool of these stateless beans to service multiple clients. An instance is taken out of the pool when a client sends a request. There is no need to initialize the bean with any information. There is implemented only a single create/ejbCreate with no parameters—containing no initialization for the bean within these methods. There is no need to implement any actions within the remove/ejbRemove, ejbPassivate, ejbActivate, and setSessionContext methods. In addition, there is no need for the intended use for these methods in a stateless session bean. Instead, these methods are used mostly for EJBs with state—for stateful session beans and entity beans. Thus, these methods should be empty or extremely simple.

Implementation Methods
Home Interface Extends javax.ejb.EJBHome and requires a single create() factory method, with no arguments, and a single remove() method.
Component Interface (remote or local) Extends javax.ejb.EJBObject for the remote interface and javax.ejb.EJBLocalObject for the local interface. It defines the business logic methods, which are implemented in the bean implementation.
Bean implementation Implements SessionBean. This class must be declared as public, contain a public, empty, default constructor, no finalize() method, and implements the methods defined in the component interface. Must contain a single ejbCreate method, with no arguments, to match the create() method in the home interface. Contains empty implementations for the container service methods, such as ejbRemove, and so on.

For more information on how to develop session beans, see Chapter 3, "Implementing Session Beans".

What is a Stateful Session Bean?

A stateful session bean maintains its state between method calls. Thus, there is one instance of a stateful session bean created for each client. Each stateful session bean contains an identity and a one-to-one mapping with an individual client. The state of this type of bean is maintained across several calls through serialization of its state, called passivation. This is why the state that you passivate must be serializable. However, this information does not survive system crashes.

To maintain state for several stateful beans in a pool, it serializes the conversational state of the least recently used stateful bean to a secondary storage. When the bean instance is requested again by its client, the state is activated to a bean within the pool. Thus, all resources are used performantly, and the state is not lost.

The type of state that is saved does not include resources. The container invokes the ejbPassivate method within the bean to provide the bean with a chance to clean up its resources, such as sockets held, database connections, and hash tables with static information. All these resources can be reallocated and recreated during the ejbActivate method.


Note:

You can turn off passivation for stateful session beans.

If the bean instance fails, the state can be lost—unless you take action within your bean to continually save state. However, if you must make sure that state is persistently saved in the case of failovers, you may want to use an entity bean for your implementation. Alternatively, you could also use the SessionSynchronization interface to persist the state transactionally.

For example, a stateful session bean could implement the server side of a shopping cart on-line application, which would have methods to return a list of objects that are available for purchase, put items in the customer's cart, place an order, change a customer's profile, and so on.

Implementation Methods
Home Interface Extends javax.ejb.EJBHome and requires one or more create() factory methods, and a single remove() method.
Component Interface (remote or local) Extends javax.ejb.EJBObject for the remote interface and javax.ejb.EJBLocalObject for the local interface. It defines the business logic methods, which are implemented in the bean implementation.
Bean implementation Implements SessionBean. This class must be declared as public, contain a public, empty, default constructor, no finalize() method, and implement the methods defined in the remote interface. Must contain ejbCreate methods equivalent to the create() methods defined in the home interface. That is, each ejbCreate method is matched—by its parameter signature—to a create method defined in the home interface. Implements the container service methods, such as ejbRemove, and so on. Also, implements the SessionSynchronization interface for Container-Managed Transactions, which includes afterBegin, beforeCompletion, and afterCompletion.

For more information on how to develop session beans, see Chapter 3, "Implementing Session Beans".

What is an Entity Bean?

An entity bean is a complex business entity. An entity bean models a business entity or models multiple actions within a business process. Entity beans are often used to facilitate business services that involve data and computations on that data. For example, an application developer might implement an entity bean to retrieve and perform computation on items within a purchase order. Your entity bean can manage multiple, dependent, persistent objects in performing its necessary tasks.

An entity bean is a remote object that manages persistent data, performs complex business logic, potentially uses several dependent Java objects, and can be uniquely identified by a primary key. Entity beans are normally coarse-grained persistent objects, because they utilize persistent data stored within several fine-grained persistent Java objects.

Entity beans are persistent because they do survive a server crash or a network failure. When an entity bean is re-instantiated, the state of previous instances is automatically restored.

For detailed information on how to create entity beans, see Chapter 4, "Entity Beans".

Entity Beans are Uniquely Identified by a Primary Key

Each entity bean has a persistent identity associated with it. That is, the entity bean contains a unique identity that can be retrieved if you have the primary key—given the primary key, a client can retrieve the entity bean. If the bean is not available, the container instantiates the bean and repopulates the persistent data for you.

The type for the unique key is defined by the bean provider.


Note:

For more information on primary keys, see "How to Define and Use Primary Keys for Your Entity Bean".

Managing the Persistent Data Within the Entity Bean

The persistence for entity bean data is provided both for saving state when the bean is passivated and for recovering the state when a failover has occurred. Entity beans are able to survive because the data is stored persistently by the container in some form of data storage system, such as a database. Entity beans persist business data using one of the two following methods:

  • Automatically by the container using a container-managed persistent (CMP) entity bean.

  • Programmatically through methods implemented in a bean-managed persistent (BMP) entity bean. These methods use JDBC or SQLJ to manage persistence.

An entity bean manages its data persistence through callback methods, which are defined in the javax.ejb.EntityBean interface. When you implement the EntityBean interface in your bean class, you develop each of the callback functions as designated by the type of persistence that you choose: bean-managed persistence or container-managed persistence. The container invokes the callback functions at designated times.

The javax.ejb.EntityBean interface has the following definition:

public interface javax.ejb.EntityBean extends javax.ejb.EnterpriseBean {
   public abstract void ejbActivate(); 
   public abstract void ejbLoad();
   public abstract void ejbPassivate();
   public abstract void ejbRemove();
   public abstract void ejbStore();
   public abstract void setEntityContext(EntityContext ctx);
   public abstract voic unsetEntityContext();
}

The container expects these methods to have the following functionality:

Table 1-2 A Description of the EJB Bean Implmentation Methods

EJB Method Description
ejbCreate You must implement an ejbCreate method corresponding to each create method declared in the home interface. When the client invokes the create method, the container first invokes the constructor to instantiate the object, then it invokes the corresponding ejbCreate method. The ejbCreate method performs the following:
  • creates any persistent storage for its data, such as database rows

  • intializes a unique primary key and returns it

ejbPostCreate The container invokes this method after the environment is set. For each ejbCreate method, an ejbPostCreate method must exist with the same arguments. This method can be used to initialize parameters within or from the entity context.
ejbRemove The container invokes this method before it ends the life of the session object. This method can perform any required clean-up, for example closing external resources such as file handles.
ejbStore The container invokes this method right before a transaction commits. It saves the persistent data to an outside resource, such as a database.
ejbLoad The container invokes this method when the data should be reinitialized from the database. This normally occurs after activation of an entity bean.
setEntityContext Associates the bean instance with context information. The container calls this method after the bean creation. The enterprise bean can store the reference to the context object in an instance variable, for use in transaction management. Beans that manage their own transactions can use the session context to get the transaction context.

You can also allocate any resources that will exist for the lifetime of the bean within this method. You should release these resources in unsetEntityContext.

unsetEntityContext Unset the associated entity context and release any resources allocated in setEntityContext.
ejbActivate The container calls this method directly before it activates an object that was previously passivated. Perform any necessary reaquisition of resources in this method.
ejbPassivate The container calls this method before it passivates the object. Release any resources that can be easily re-created in ejbActivate, and save storage space. Normally, you want to free resources that cannot be passivated, such as sockets or database connections. Retrieve these resources in the ejbActivate method.

Create the Entity Bean Using ejbCreate and ejbPostCreate

An entity bean is similar to a session bean because certain callback methods, such as ejbCreate, are invoked at specified times. Entity beans use callback functions for managing its persistent data, primary key, and context information. The following diagram shows what methods are called when an entity bean is created.

Figure 1-1 Creating the Entity Bean

Creating the Entity Bean
Description of the illustration create.gif

Retrieve the Entity Bean Context With setEntityContext

An entity bean instance uses this method to retain a reference to its context. Entity beans have contexts that the container maintains and makes available to the beans. The bean may use the methods in the entity context to retrieve information about the bean, such as security, and transactional role. Refer to the Enterprise JavaBeans specification from Sun Microsystems for the full range of information that you can retrieve about the bean from the context.

The container invokes the setEntityContext method, after it first instantiates the bean, to enable the bean to retrieve the context. The container will never call this method from within a transaction context. If the bean does not save the context at this point, the bean will never gain access to the context.


Note:

You can also use the setEntityContext and unsetEntityContext methods to allocate and destroy any resources that will exist for the lifetime of the instance.

When the container calls this method, it passes the reference of the EntityContext object to the bean. The bean can then store the reference for later use. The following example shows the bean saving the context in the this.ctx variable.

public void setEntityContext(EntityContext ctx) { this.ctx = ctx; }

Remove the Entity Bean With ejbRemove

When the client invokes the remove method, the container invokes the methods shown in Figure 1-2.

Figure 1-2 Removing the Entity Bean

Removing the Entity Bean
Description of the illustration overview2.gif

Manage the Persistent Data With ejbStore and ejbLoad

In addition, the ejbStore and ejbLoad methods are called for managing your persistent data. These are the most important callback methods—for bean-managed persistent beans. Container-managed persistent beans can leave these methods empty, because the persistence is managed by the container.

  • The ejbStore method is called by the container before the object is passivated or whenever a transaction is about to end. Its purpose is to save the persistent data to an outside resource, such as a database.

  • The ejbLoad method is called by the container before the object is activated or whenever a transaction has begun, or when an entity bean is instantiated. Its purpose is to restore any persistent data that exists for this particular bean instance.

Manage Your Persistent Data With Container-Managed Persistence

You can choose to have the container manage your persistent data for the bean. You do not have to implement some of the callback methods to manage persistence for your bean's data, because the container stores and reloads your persistent data to and from the database. When you use container-managed persistence, the container invokes a persistence manager class that provides the persistence management business logic. In addition, you do not have to provide management for the primary key: the container provides this key for the bean.

  • Callback methods—The container still invokes the callback methods, so you can add logic for other purposes. At the least, you must provide an empty implementation for all callback methods.

  • Primary key—The primary key fields in a CMP bean must be declared as container-managed persistent fields in the deployment descriptor. All fields within the primary key are restricted to be either primitive, serializable, and types that can be mapped to SQL types.


    Note:

    For more information on primary keys, see "How to Define and Use Primary Keys for Your Entity Bean".

The following table details the implementation requirements for the callback functions of the bean class:

Callback Method Functionality Required
ejbCreate You must initialize all container-managed persistent fields, including the primary key.
ejbPostCreate You have the option to provide any additional initialization, which can involve the entity context.
ejbRemove No functionality for removing the persistent data from the outside resource is required. You must at least provide an empty implementation for the callback, which means that you can add logic for performing any cleanup functionality you require.
ejbFindByPrimaryKey No functionality is required for returning the primary key to the container. The container manages the primary key—after it is initialized by the ejbCreate method. You still must provide an empty implementation for this method.
ejbStore No functionaltiy is required for saving persistent data within this method. The persistent manager saves all persistent data to the database for you. However, you must provide at least an empty implementation.
ejbLoad No functionality is required for restoring persistent data within this method. The persistence manager restores all persistent data for you. However, you must provide at least an empty implementation.
setEntityContext Associates the bean instance with context information. The container calls this method after the bean creation. The enterprise bean can store the reference to the context object in an instance variable, for use in transaction management. Beans that manage their own transactions can use the session context to get the transaction context.

You can also allocate any resources that will exist for the lifetime of the bean within this method. You should release these resources in unsetEntityContext.

unsetEntityContext Unset the associated entity context and release any resources allocated in setEntityContext.


Note:

For more information on container-managed persistence, see Chapter 5, "CMP Entity Beans".

What is the Difference Between Session and Entity Beans?

The major differences between session and entity beans are that entity beans involve a framework for persistent data management, a persistent identity, and complex business logic. The following table illustrates the different interfaces for session and entity beans. Notice that the difference between the two types of EJBs exists within the bean class and the primary key. All of the persistent data management is done within the bean class methods.

J2EE Subject Entity Bean Session Bean
Local interface Extends javax.ejb.EJBLocalObject Extends javax.ejb.EJBLocalObject
Remote interface Extends javax.ejb.EJBObject Extends javax.ejb.EJBObject
Local Home interface Extends javax.ejb.EJBLocalHome Extends javax.ejb.EJBLocalHome
Remote Home interface Extends javax.ejb.EJBHome Extends javax.ejb.EJBHome
Bean class Extends javax.ejb.EntityBean Extends javax.ejb.SessionBean
Primary key Used to identify and retrieve specific bean instances Not used for session beans. Stateful session beans do have an identity, but it is not externalized.

When Do You Use a Message-Driven Bean?

Message-Driven Beans (MDB) provide an easier method to implement asychronous communication than using straight JMS. MDBs were created to receive asynchronous JMS messages. The container handles much of the setup required for JMS queues and topics. It sends all messages to the interested MDB.

Previously, EJBs could not send or receive JMS messages. It took creating MDBs for an EJB-type object to receive JMS messages. This provides all of the asynchronous and publish/subscribe abilities to an enterprise object that is able to be synchronous with other Java objects.

The purpose of an MDB is to exist within a pool and to receive and process incoming messages from a JMS queue. The container invokes a bean from the queue to handle each incoming message from the queue. No object invokes an MDB directly: all invocation for an MDB comes from the container. After the container invokes the MDB, it can invoke other EJBs or Java objects to continue the request.

A MDB is similar to a stateless session bean because it does not save conversational state and is used for handling multiple incoming requests. Instead of handling direct requests from a client, MDBs handle requests placed on a queue. Figure 1-3 demonstrates this by showing how clients place requests on a queue. The container takes the requests off of the queue and gives the request to an MDB in its pool.

Figure 1-3 Message Driven Beans

Message Driven Beans
Description of the illustration overview3.gif

MDBs implement the javax.ejb.MessageDrivenBean interface, which also inherits the javax.jms.MessageListener methods. Within these interfaces, the following methods must be implemented:

Method Description
onMessage(msg) The container dequeues a message from the JMS queue associated with this MDB and gives it to this instance by invoking this method. This method must have an implementation for handling the message appropriately.
setMessageDrivenContext(ctx) After the bean is created, the setMessageDrivenContext method is invoked. This method is similar to the EJB setSessionContext and setEntityContext methods.
ejbCreate() This method is used just like the stateless session bean ejbCreate method. No initialization should be done in this method. However, any resources that you allocate within this method will exist for this object.
ejbRemove() Delete any resources allocated within the ejbCreate method.

The container handles JMS message retrieval and acknowledgment. Your MDB does not have to worry about JMS specifics. The MDB is associated with an existing JMS queue. Once associated, the container handles dequeuing messages and sending acknowledgments. The container communicates the JMS message through the onMessage method.


Note:

For more information on MDBs and how to implement them, see Chapter 9, "Message-Driven Beans".