Skip Headers
Oracle® Application Server Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 2 (10.1.2)
Part No. B15505-02
  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
 

1 How Do Applications Use EJBs?

This chapter discusses EJB concepts that are specified fully in the J2EE specification. The remainder of the chapters in this book show only the tasks necessary to develop your EJBs.

For more details and examples of the concepts presented in this chapter, refer to books written by Sun Microsystems that discuss EJBs and J2EE Blueprint Architecture recommendations.

This chapter includes the following topics:

New Features of EJB 2.0

The following sections describe the new features to EJB 2.0:

Local Interface Support

Oracle Application Server provides complete support for local interfaces.

A client may access a session or an entity bean only through the methods defined in the bean's interfaces which define the client's view of a bean. All other aspects of the bean - method implementations, deployment descriptor settings, abstract schemas, database access calls - are hidden from the client providing modularity and encapsulation. Well designed interfaces simplify the development and maintenance of J2EE applications by shielding clients from any complexities in the business logic and also allowing the EJBs to change internally without affecting the clients. EJBs support two types of client access - remote or local.

Remote Access

A remote client of an enterprise bean has the following traits:

  1. It may run on a different machine and a different Java Virtual Machine (JVM) than the enterprise bean it accesses.

  2. It can be a Web component, a J2EE application client, or another enterprise bean.

  3. To a remote client, the location of the enterprise bean is transparent. To create an enterprise bean with remote access, you must code a remote interface and a home interface. The remote interface defines the business methods that are specific to the bean.

Local Access

A local client has these characteristics:

  1. It must run in the same JVM as the enterprise bean it accesses.

  2. It may be a web component or another enterprise bean.

  3. To the local client, the location of the enterprise bean it accesses is not transparent.

  4. It is often an entity bean that has a container-managed relationship with another entity bean. To build an enterprise bean that allows local access, you must code a local interface and a local home interface. The local interface defines the bean's business methods and the local home interface defines its life-cycle and finder methods.

Local Interfaces and Container-Managed Relationships

If an entity bean is the target of a container-managed relationship, then it must have local interfaces. Further, if the relationship between the EJBs is bidirectional, both beans must have local interfaces. Moreover, since they require local access, entity beans that participate in a container-managed relationship must reside in the same EJB container. The primary benefit of this locality is increased performance - local calls are usually faster than remote calls.

Local Compared to Remote Access

The decision on whether to allow local or remote access depends on the following factors:

  1. Container-Managed Relationships - If an entity bean is the target of a container-managed relationship, it must use local access.

  2. Tight or Loose Coupling of Related Beans - tightly coupled beans depend on one another. For example, a completed sales order must have one or more line items, which cannot exist without the order to which they belong. The OrderEJB and LineItemEJB beans that model this relationship are tightly coupled. Tightly coupled beans are good candidates for local access. Since they fit together as a logical unit, they probably call each other often and would benefit from the increased performance that is possible with local access.

Home Interface Business Methods

Home interface business methods are used for public usage of methods that do not use entity bean persistent data. If you want to supply methods that perform duties for you that are not associated with any specific bean, a home interface business method allows you to publicize this method.

Message-Driven Beans

You can implement EJB 2.0 message-driven beans with Oracle JMS. A full example is provided in Chapter 9, "Message-Driven Beans".

Enterprise JavaBeans Query Language (EJB QL)

EJB QL defines the queries for the finder and select methods of an entity bean with container-managed persistence. A subset of SQL92, EJB QL has extensions that allow navigation over the relationships defined in an entity bean's abstract schema. The abstract schema is part of an entity bean's deployment descriptor and defines the bean's persistent fields and relationships. The term "abstract" distinguishes this schema from the physical schema of the underlying datastore. The abstract schema name is referenced by EJB QL queries since the scope of an EJB QL query spans the abstract schemas of related entity beans that are packaged in the same EJB JAR file. For an entity bean with container-managed persistence, an EJB QL query must be defined for every finder method (except findByPrimaryKey). The EJB QL query determines the query that is executed by the EJB container when the finder method is invoked.

Oracle Application Server provides complete support for EJB QL with the following important features:

  • Automatic Code Generation: EJB QL queries are defined in the deployment descriptor of the entity bean. When the EJBs are deployed to Oracle Application Server, the container automatically translates the queries into the SQL dialect of the target data store. Because of this translation, entity beans with container-managed persistence are portable -- their code is not tied to a specific type of data store.

  • Optimized SQL Code Generation: Further, in generating the SQL code, Oracle Application Server makes several optimizations such as the use of bulk SQL, batched statement dispatch, and so on to make database access efficient.

  • Support for Oracle and Non-Oracle Databases: Further, Oracle Application Server provides the ability to execute EJB QL against any database - Oracle, MS SQL-Server, IBM DB/2, Informix, and Sybase.

  • CMP with Relationships: Oracle Application Server supports EJB QL for both single entity beans and also with entity beans that have relationships, with support for any type of multiplicity and directionality.

See Chapter 7, "EJB Query Language" for more information and examples.

CMP Relationships

The EJB 2.0 specification enables the specification of relationships between entity beans. An entity bean can be defined so as to have a relationship with other entity beans. For example, in a project management application the ProjectEJB and TaskEJB beans would be related because a project is made up of a set of tasks. You implement relationships differently for entity beans with bean-managed-persistence than those entity beans that utilize container-managed-persistence. With bean-managed persistence, the code that you write implements the relationships. With container-managed persistence, the EJB container takes care of the relationships for you. For this reason, relationships in entity beans with container-managed persistence are often referred to as container-managed relationships.

  • Relationship Fields - A relationship field in an EJB identifies a related bean. A relationship field is virtual and is defined in the enterprise bean class with access methods. Unlike a persistent field, a relationship field does not represent the bean's state.

  • Multiplicity in Container-Managed Relationships - There are four types of multiplicities all of which are supported by Oracle Application Server:

    • One-to-One - Each entity bean instance is related to a single instance of another entity bean.

    • One-to-Many - An entity bean instance is related to multiple instances of the other entity bean.

    • Many-to-One - Multiple instances of an entity bean may be related to a single instance of the other entity bean. This multiplicity is the opposite of one-to-many.

    • Many-to-Many - The entity bean instances may be related to multiple instances of each other.

  • Direction in Container-Managed Relationships - The direction of a relationship may be either bi-directional or unidirectional. In a bi-directional relationship, each entity bean has a relationship field that refers to the other bean. Through the relationship field, an entity bean's code can access its related object. If an entity bean has a relative field, then we often say that it "knows" about its related object. For example, if an ProjectEJB bean knows what TaskEJB beans it has and if each TaskEJB bean knows what ProjectEJB bean it belongs to, then they have a bi-directional relationship. In a unidirectional relationship, only one entity bean has a relationship field that refers to the other. Oracle Application Server supports both unidirectional and bi-directional relationships between EJBs.

  • EJBQL and CMP With Relationships - EJB QL queries often navigate across relationships. The direction of a relationship determines whether a query can navigate from one bean to another. With Oracle Application Server, EJBQL queries can traverse CMP Relationships with any type of multiplicity and with both unidirectional and bi-directional relationships.

For more information, see Chapter 4, "CMP Entity Beans", Chapter 6, "Entity Relationship Mapping", and Chapter 7, "EJB Query Language".

Oracle Application Server Object-Relational Mapping

Oracle Application Server furnishes, out of the box, its own persistence manager for entity beans, which supplies both simple (1:1) mapping and complex relationship (1:n, m:n) mapping. Oracle Application Server provides complete support for the EJB 2.0 O-R mapping specification.

For more information, see Chapter 6, "Entity Relationship Mapping".

Third Party O-R Mappings - TopLink Integration

Oracle Application Server integrates leading third party O-R mapping solutions including TopLink for Java, with the EJB container. TopLink provides developers with the flexibility to map objects and Enterprise Java Beans to a relational database schema with minimal impact. TopLink for Java provides advanced mapping capabilities such as bean/object identity mapping, type and value transformation, relationship mapping (1:1, 1:n and m:n), object caching and locking, batch writing, and advanced and dynamic query capabilities. TopLink offers a GUI mapping tool - the TopLink Mapping Workbench - which simplifies the process of mapping J2EE components to database objects. TopLink provides EJB 2.0 support, automatic or developer-configured bi-directional relationship maintenance, automatic or developer-configured cache synchronization session management via XML, and optimistic read locking. Oracle Application Server is also integrated with other leading O-R mapping solutions in the market.

For more information on TopLink, see the Oracle Application Server TopLink Getting Started Guide.

CORBA Support - RMI-over-IIOP

RMI over IIOP is part of the J2EE 1.3 Specification and provides two important benefits:

  • RMI over IIOP provides the ability to write CORBA applications for the Java platform without learning CORBA Interface Definition Language (IDL).

  • IIOP eases legacy application and platform integration by allowing applications written in C++, Smalltalk, and other CORBA supported languages to communicate with J2EE components.

Oracle Application Server supports RMI-over-IIOP providing the following important facilities:

  • Automatic IDL Stub and Helper Class Generation - To work with CORBA applications in other languages, IDL, CORBA stubs and skeletons can be generated:

    1. Automatically by Oracle Application Server when the J2EE Application is deployed to it.

    2. IDL can also be generated from J2EE interfaces using the rmic compiler with the -idl option. Further, developers can use the rmic compiler with the -iiop option to generate IIOP stub and tie classes, rather than Java Remote Messaging Protocol (JRMP) stub and skeleton classes.

  • Objects-By-Value - The Oracle Application Server RMI-IIOP implementation provides flexibility by allowing developers to pass any serializable Java object (Objects By Value) between application components.

  • POA Support - The Portable Object Adapter (POA) is designed to provide an object adapter that can be used with multiple ORB implementations with a minimum of rewriting needed to deal with different vendors' implementations. The POA is also intended to allow persistent objects -- at least, from the client's perspective. That is, as far as the client is concerned, these objects are always alive, and maintain data values stored in them, even though physically, the server may have been restarted many times, or the implementation may be provided by many different object implementations. Oracle Application Server provides complete POA support.

  • Interoperating with Other ORBs - The Oracle Application Server RMI-IIOP implementation will interoperate with other ORBs that support the CORBA 2.3 specification. It will not interoperate with older ORBs, because these are unable to handle the IIOP encodings for Objects By Value. This support is needed to send RMI value classes (including strings) over IIOP. Oracle Application Server also provides complete support for the Interoperable Naming, Security, and Transactions elements in the J2EE 1.3 specification allowing developers to build J2EE applications and interoperate them with J2EE applications on other Application Servers and with legacy systems through CORBA.

See the RMI/Interoperability chapter in the Oracle Application Server Containers for J2EE Services Guide for more information.

Changes in Defaults for Oracle Application Server

Default values in version 9.0.3 have been modified as follows:

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 5, "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 4, "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".

What Makes Up An EJB?

An EJB has two client interfaces that a client uses to create and use an EJB:

The client uses both of these interfaces when invoking a method on a bean.

Figure 1-4 Events in a Stateless Session Bean

Events in a Stateless Session Bean
Description of the illustration overview4.gif

Figure 1-4 demonstrates a stateless session bean and corresponds to the following steps:

  1. The client, which can be a standalone Java client, servlet, JSP, or an applet, retrieves the home interface of the bean—normally through JNDI.

  2. The client invokes the create method on the home interface reference (home object). This creates the bean instance and returns a reference to the component interface (remote or local interface) of the bean.

  3. The client invokes a method defined in the component interface (remote or local interface), which delegates the method call to the corresponding method in the bean instance (through a stub).

  4. The client can destroy the bean instance by invoking the remove method that is defined in the component interface (remote or local interface). Some beans, such as stateless session beans, cannot call the remove method. In this case, the container removes the bean.

For an example of a stateless session bean implementation, see "Developing Session Beans".

When developing an EJB, you create the following four major components:

Development issues for your EJBs are discussed in the following sections:

Interfaces for Bean Implementation is Based on Bean Type

Your bean implements the methods within either the SessionBean, EntityBean, or MessageDrivenBean interface. The implementation contains logic for lifecycle methods defined in the home interface, business methods defined in the component interface (remote or local), and container callback functions defined in the SessionBean, EntityBean, or MessageDrivenBean interface.

See the following chapters for details on each bean type:

Parameter Passing Conventions for Your EJBs

When you implement an EJB or write the client code that calls EJB methods, you must be aware of the parameter-passing conventions used with EJBs.

A parameter that you pass to a bean method—or a return value from a bean method—can be any Java type that is serializable. Java primitive types, such as int, double, are serializable. Any non-remote object that implements the java.io.Serializable interface can be passed. A non-remote object that is passed as a parameter to a bean or returned from a bean is passed by value, not by reference. So, for example, if you call a bean method as follows:

public class theNumber {
  int x;
}
...
bean.method1(theNumber);

then method1() in the bean receives a copy of theNumber. If the bean changes the value of theNumber object on the server, this change is not reflected back to the client, because of pass-by-value semantics.

If the non-remote object is complex—such as a class containing several fields—only the non-static and non-transient fields are copied.

When passing a remote object as a parameter, the stub for the remote object is passed. A remote object passed as a parameter must extend remote interfaces.

The next section demonstrates parameter passing to a bean, and remote objects as return values.

How to Handle Returned Parameter Objects

The EmployeeBean getEmployee method returns an EmpRecord object, so this object must be defined somewhere in the application. In this example, an EmpRecord class is included in the same package as the EJB interfaces.

The class is declared as public and must implement the java.io.Serializable interface so that it can be passed back to the client by value, as a serialized remote object. The declaration is as follows:

package employee;

public class EmpRecord implements java.io.Serializable {
  public String ename;
  public int empno;
  public double sal;
}

Note:

The java.io.Serializable interface specifies no methods; it just indicates that the class is serializable. Therefore, there is no need to implement extra methods in the EmpRecord class.

What Container Services Can You Use for EJBs?

One of the advantages of using EJBs is that the EJB container provides security and transaction services for you. These services, as well as RMI/IIOP, JNDI, Data Source, and JMS, are documented in the following books: