Sun ONE logo     Previous      Contents      Index      Next     
Sun ONE Application Server 7 Developer's Guide to Enterprise Java Beans Technology



Using Session Beans

This section provides guidelines for creating session beans in the Sun ONE Application Server 7 environment.



Note

If you are unfamiliar with session beans or the EJB technology, refer to the Java Software tutorials:

http://java.sun.com/j2ee/docs.html

Extensive information on session beans is contained in chapters 6, 7, and 8 of the Enterprise JavaBeans Specification, v2.0.

Overview material on the Sun ONE Application Server is contained in "Introducing the Sun ONE Application Server Enterprise JavaBeans Technology" and the Sun ONE Application Server Product Introduction.



This section addresses the following topics:

Extensive information on session beans is contained in the chapters 6, 7, and 8 of the Enterprise JavaBeans Specification, v2.0.

About Session Beans

This section provides an overview of what you need to be aware of about session beans in order to develop effective models for your business processes.

This section addresses the following topics:

Session Bean Characteristics

The defining characteristics of a session bean have to do with its non-persistent, independent status within an application. One way to think of a session bean is as a temporary, logical extension of a client application that runs on the Sun ONE Application Server. Generally, a session bean does not represent shared data in a database, but obtains a data snapshot. However, a session bean can update data.

Session beans have the following characteristics:

  • Execute for a single client.
  • Can be transaction aware.
  • Do not represent directly shared data in an underlying database, although they may access and update this data.
  • Are short lived.
  • Are not persisted in a database.
  • Are removed if the container crashes; the client has to establish a new session.

Much of a standard, distributed application consists of logical code units that perform repetitive, time-bound, and user-dependent tasks. These tasks can be simple or complex, and are often needed in different applications. For example, banking applications must verify a user's account ID and balances before performing any transaction. Such discrete tasks, transient by nature, are candidates for session beans.

Sample Scenario

The shopping cart employed by many web-based, online shopping applications is a typical use for a session bean. It is created by the online shopping application only when an item is selected by the user. When selection is completed, the item prices in the cart are calculated, the order is placed, and the shopping cart object is released, or freed. A user can continue browsing merchandise in the online catalog, and if the user decides to place another order, a new shopping cart is created.

Often, a session bean has no dependencies on or connections to other application objects. For example, a shopping cart bean might have a data list member for storing item information, a data member for storing the total cost of items currently in the cart, and methods for adding, subtracting, reporting, and totaling items. On the other hand, the shopping cart might not have a live connection to the database at all.

The Container

Like an entity bean, a session bean can access a database through JDBC calls. A session bean can also provide transaction settings. These transaction settings and JDBC calls are referenced by the session bean's container, allowing it to participate in transaction managed by the container.

A container managing stateless session beans has a different charter from a container managing stateful session beans.

Stateless Container

The stateless container manages the stateless session beans, which, by definition, do not carry client-specific states. Therefore, all session beans (of a particular type) are considered equal.

A stateless session bean container uses a bean pool to service requests. The Sun ONE Application Server-specific XML file contains the properties that define the pool:

  • steady-pool-size
  • resize-quantity
  • max-pool-size
  • pool-idle-timeout-in-seconds   

These properties are defined for the deployment descriptor in "Elements in the sun-ejb-jar.xml File"."

Stateful Container

The stateful container manages the stateful session beans, which, by definition, carry the client-specific state. There is a one-to-one relationship between the client and the stateful session beans. At creation, each stateful session bean is given a unique session ID that is used to access the session bean so that an instance of a stateful session bean is accessed by a single client only.

Stateful session beans are managed using cache. The size and behavior of stateful session beans cache can be controlled by specifying the following parameters:

  • max-cache-size
  • resize-quantity
  • cache-idle-timeout-in-seconds
  • removal-timeout-in-seconds
  • victim-selection-policy

The max-cache-size element specifies the maximum number of session beans that are held in cache. If the cache overflows (when the number of beans exceeds max-cache-size), the container then passivates some beans or writes out the serialized state of the bean into a file. The directory in which the file is created is obtained from the server.xml file using the configuration APIs.

These properties are defined in the deployment descriptor. See "Elements in the sun-ejb-jar.xml File" for more information.

The passivated beans are stored on the file system.The session-store attribute in the server element in the server.xml file allows the administrator to specify the directory where passivated beans are stored. By default, passivated stateful session beans are stored in application-specific subdirectories created under instance_dir/session-store.

Developing Session Beans

When a client is done with the session bean, it is released, or freed. When designing an application, you should designate each temporary, single client object as a potential session bean.

The following sections discuss how to develop effective session beans:

Development Requirements

When developing a session bean, you must provide the following:

  • Session bean's remote interface and remote home interface, if the session bean provides a remote client view
  • Session bean's local interface and local home interface, if the session bean provides a local client view
  • Bean class implementation
  • Assembly and deployment data

Requirements of a session bean implementation class:

  • Implements the javax.ejb SessionBean interface.
  • The class is defined as public, and cannot be defined as abstract or final.
  • Implements one ejbCreate method that takes no arguments.
  • Implements the business methods.
  • Contains a public constructor with no parameters.
  • Must not define the finalize method.

Determining Session Bean Usage

This section provides some guidelines for determining whether to implement stateful or stateless session beans.

Stateful Session Bean Considerations

Stateful session beans are appropriate if any of the following conditions are true:

  • The bean's state represents the interaction between the bean and a specific client.
  • The bean needs to hold information about, or on behalf of, the client user conversational state across method invocations.
  • The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
  • Behind the scenes, the bean manages the work flow of several enterprise beans.

Because stateful session beans are private to a client, their demand on server resources increases as the number of users accessing an application increases. The beans remain in the container until they are explicitly removed by the client, or are removed by the container when they timeout.

The container needs to passivate stateful session beans to secondary storage as its cache fills up and the beans in the cache timeout. If the client subsequently accesses the bean, the container is responsible for activating the bean. This passivation/activation process imposes a performance overhead on the server.

Stateless Session Bean Considerations

You might choose a stateless session bean if any of these conditions exist:

  • The bean's state has no data for a specific client, that is, user conversational state does not have to be retained across method invocations on the bean.
  • In a single method invocation, the bean performs a generic task for all clients.
  • The bean fetches a set of read-only data (from a database) that is often used by clients. Such a bean, for example, could retrieve the table rows that represent the products that are on sale this month.

Use a stateless session bean to access data or perform transactional operations. Stateless session beans provide high scalability because a small number of such beans managed by the container in a stateless bean pool) can help serve a large number of clients. This is possible because stateless beans have no association with the clients. When a request for a service provided by a stateless session bean is received, the container is free to dispatch the request to any bean instance in the pool.

  • The create method of the remote home interface must return the session bean's remote interface.
  • The create method of the local interface must return the session bean's local interface.
  • There can be no other create methods in the home interface.
  • A stateless session bean must not implement the javax.ejb.SessionSynchronization interface.

Providing Interfaces

As the developer, you are responsible for providing interfaces for the bean. If you implement a remote view for your bean, provide a remote component interface and a remote home interface. If you implement a local view, provide a local component interface and a local home interface.

To use interfaces safely, you need to carefully consider potential deployment scenarios, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind.

The following sections discuss creating interfaces:

Creating a Remote Interface

A session bean's remote interface defines a user's access to a bean's methods. All remote interfaces extend javax.ejb.EJBObject. For example:

   import javax.ejb.*;
   import java.rmi.*;
   public interface MySession extends EJBObject {
   // define business method methods here....
   public String getACcountname() throws RemoteException;
   }

The remote interface defines the session bean's business methods that a client calls. For each method you define in the remote interface, you must supply a corresponding method in the bean class itself. The corresponding method in the bean class must have the same signature, the same parameter types and return type. The name of the method has ejb preprended to it. For example, the implementation class for MySession includes the method:

   String ejbgetAccountname() throws RemoteException
   {
   method implementation
   }

Creating a Local Interface

The local interface may be defined for a bean during development to allow streamlined calls to the bean if a caller is in the same container, that is, running in the same address space or Java Virtual Machine (JVM). This improves the performance of applications in which co-location is planned.

However, the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using pass-by-value semantics, while local interfaces use pass-by-reference. As a developer, you must be aware of the potential sharing of objects passed through the local interface. In particular, be careful that the state of one enterprise bean is not assigned to the state of another. You must also exercise caution in determining which objects to pass across the local interface, particularly in the case where there is a change in transaction or security content.

The local interface extends the javax.ejb.EJBLocalObject interface, and is allowed to have super interfaces. The throws clause of a method defined in the local interface must not include java.rmi.RemoteException. For example:

   import javax.ejb.*;
      public interface MyLocalSession extends EJBLocalObject {
   // define business method methods here....
   }

For each method defined in the local interface, there must be a matching method in the session bean's class. The matching method must have the same name, the same number and types of arguments, and the same return type. All exceptions defined in the throws clause of the matching method of the session bean class must be defined in the throws clause of the method of the local interface. The methods should not throw java.rmi.RemoteException.

Creating the Local Home Interface

The home interface defines the methods that enable a client using the application to create and remove session beans. An enterprise bean's local home interface defines the methods that allow local clients to create, find, and remove EJB objects, as well as home business methods that are not specific to a bean instance (session beans do not have finders and home business methods). The local home interface is defined by you and implemented by the container. A client locates a session bean's home interface using JNDI.

The local home interface allows a local client to:

  • Create a new session object
  • Remove a session object

A local home interface always extends javax.ejb.EJBLocalHome. For example:

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

   public interface MySessionLocalBeanHome extends EJBLocalHome {
      MySessionLocalBean create() throws CreateException;
   }

Create Methods

As this example illustrates, a session bean's home interface defines one or more create methods. Each method must be named create, and must correspond in number and argument types to an ejbCreate method defined in the session bean class. The return type for each create method, however, does not match its corresponding ejbCreate method's return type. Instead, it must return the session bean's local interface type.

All exceptions defined in the throws clause of an ejbCreate method must be defined in the throws clause of the matching create method in the remote interface. In addition, the throws clause in the home interface must always include javax.ejb.CreateException.

Remove Methods

A remote client may remove a session object using the remove method on the javax.ejb.EJBObject interface, or the remove(Handle handle) method of the javax.ejb.EJBHome interface.

Because session objects do not have primary keys that are accessible to clients, invoking the javax.ejb.EBJHome.remove(Object primaryKey) method on a session results in javax.ejbRemoveException.

Creating the Remote Home Interface

The container provides the implementation of the remote home interface for each session bean that defines a remote home interface that is deployed in the container. The object that implements this is called a session EJBHome object. The remote home interface allows a client to do the following:

  • Create a new session object
  • Remove a session object
  • Get the javax.ejb.EJBMetaData interface for the session bean
  • Obtain a handle for the remote home interface

The remote home interface must extend the javax.ejb.EJBHome interface, and is allowed to have super interfaces. The methods defined in the interface must follow the rules for RMI/IIOP.

The remote home interface must define one or more create<METHOD>(...) methods.

A remote home interface always extends javax.ejb.EJBHome. For example:

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

   public interface MySessionHome extends EJBHome {
      MySession create() throws CreateException, RemoteException;
   }

As this example illustrates, a session bean's home interface defines one or more create methods. The return type for each create method, however, does not match its corresponding ejbCreate method's return type. Instead, it must return the session bean's remote interface type.

All exceptions defined in the throws clause of an ejbCreate method must be defined in the throws clause of the matching create method in the remote interface. In addition, the throws clause in the home interface must always include javax.ejb.CreateException and java.rmi.RemoteException.



Note

For stateless session beans, the home interface must have exactly one create method and the bean must have exactly one ejbCreate method. Both methods take no arguments.



Creating the Bean Class Definition

For a session bean, the bean class must be defined as public, must not be final, and cannot be abstract. The bean class must implement the javax.ejb.SessionBean interface.

import java.rmi.*;
import java.util.*;
import javax.ejb.*;
public class MySessionBean implements SessionBean {
   // Session Bean implementation. These methods must always     included.
   public void ejbActivate() {
   }
   public void ejbPassivate() {
   }
   public void ejbRemove() {
   }
   public void setSessionContext(SessionContext ctx) {
   }
   
   // other code omitted here....
   }

The session bean must implement one or more ejbCreate(...) methods. There must be one method for each way a client invokes the bean. For example:

   public void ejbCreate() {         
      string[] userinfo = {"User Name", "Encrypted Password"} ;
   }

Each ejbCreate(...) method must be declared as public, return void, and be named ejbCreate. Arguments must be legal Java RMI types. The throws clause may define application specific exceptions and java.ejb.CreateException.

Session beans also implement one or more business methods. These methods are usually unique to each bean and represent its particular functionality. For example, if a session bean manages user logins, it might include a unique function called validateLogin.

Business method names can be anything, but must not conflict with the method names defined in the EJB interfaces. Business methods must be declared as public. Method arguments and return value types must be legal for Java RMI. The throws clause may define application specific exceptions.

Session Synchronization

There is one interface implementation permitted in a stateful session bean class definition, particularly javax.ejb.SessionSynchronization, that enables a session bean instance to be notified of transaction boundaries and synchronize its state with those transactions.

The javax.ejb.SessionSynchronization interface allows a stateful session bean instance to be notified by its container of transaction boundaries. A session bean class is optional to implement this interface. A session bean class should implement this interface only if you want to synchronize its state with the transactions. For example, a stateful session bean that implements this interface will get callbacks after a new transaction begins, but before a transaction commits, and after commitment.

For more information about this interface, see the Enterprise JavaBeans Specification, v2.0.



Note

The container will only invoke the session synchronization interface methods for stateful session beans that use container-managed transactions.



Abstract Methods

Besides the business methods you define in the remote interface, the EJBObject interface defines several abstract methods that enable you to:

  • Retrieve the bean's home interface
  • Retrieve the bean's handle (a unique identifier)
  • Compare the bean to another bean to see if it is identical
  • Free or remove the bean when it is no longer needed.

For more information about these built-in methods and how they can be used, see the Enterprise JavaBeans Specification, v2.0.

The deployment tools provided by the container are responsible for the generation of additional classes when the session bean is deployed.

Restrictions and Optimizations

This section discusses restrictions on developing session beans and provides some optimization guidelines:

Optimizing Session Bean Performance

For stateful session beans, co-locating the stateful beans with their clients so that the client and bean are executing in the same process address space will improve performance.

Restricting Transactions

The following restrictions on transactions are enforced by the container and must be observed as you develop session beans:

  • A session bean can participate in, at most, a single transaction at a time.
  • If a session bean is participating in a transaction, a client cannot invoke a method on the bean such that the transaction attribute in the deployment descriptor would cause the container to execute the method in a different or unspecified transaction context or an exception is thrown.
  • If a session bean instance is participating in a transaction, a client cannot invoke the remove method on the session object's home or component interface object or an exception is thrown.

Previous      Contents      Index      Next     
Copyright 2002 Sun Microsystems, Inc. All rights reserved.