Enterprise JavaBeans - Part 2

Differences Between JavaBeans and Enterprise JavaBeans

Table 1 summarizes some of the major differences between a JavaBean and an Enterprise JavaBean.

JavaBeans
Enterprise JavaBeans

JavaBeans may be visible or nonvisible at runtime. For example, the visual GUI component may be a button,list box,graphic,or a chart.
An EJB is a nonvisual,remote object.

JavaBeans are intended to be local to a single process and are primarily intended to run on the client side. Although one can develop server-side JavaBeans, it is far easier to develop them using the EJB specification instead.
EJBs are remotely executable components or business objects that can be deployed only on the server.

JavaBeans is a component technology to create generic Java components that can be composed together into applets and applications.Even
though EJB is a component technology,it neither builds upon nor extends the original JavaBean specification.

JavaBeans have an external interface called the Properties interface, which allows a builder tool to interpret the functionality of the bean.
EJBs have a deployment descriptor that describes its functionality to an external builder tool or IDE.

JavaBeans may have BeanInfo classes,property editors,or customizers.
EJBs have no concept of BeanInfo classes,property editors,or customizers and provide no additional information other than that described in the deployment descriptor.

JavaBeans are not typed.
EJBs are of two types—session beans and entity beans.

No explicit support exists for transactions in JavaBeans.
EJBs may be transactional and the EJB Servers provide transactional support.

Component bridges are available for JavaBeans.For example,a JavaBean can also be deployed as an ActiveX control.
An EJB cannot be deployed as an ActiveX control because ActiveX controls are intended to run at the desktop and EJBs are server side components.However,CORBA-IIOP compatibility via the EJB-to-CORBA mapping is defined by the OMG.

Table 1: Differences between JavaBeans and Enterprise JavaBeans

Enterprise JavaBeans - Part 2

The EJB Model

A basic EJB architecture is shown in Figure 2 and consists of:

An EJB server
EJB containers that run within the server
Home objects, remote EJBObjects, and enterprise beans that run within containers
EJB clients
Auxiliary systems like JNDI, JTS, security services, and so forth.

Figure 2: The basic Enterprise JavaBean architecture

Now, let’s examine the primary components of the EJB architecture in greater detail:

EJB Server

The EJB server provides an organized framework or execution environment in which EJB containers can run. It makes available system services for multiprocessing, load balancing, and device access for EJB containers. The EJB server also makes EJB containers running within them visible to the outside world. It may also provide vendor-specific features like an optimized data access interface, additional CORBAServices, SSL support, a JNDI-accessible naming service, and transaction management services.

In some respects, the EJB server is analogous to CORBA’s Object Transaction Monitor (OTM). The OTM, too, provides an execution framework for running server side CORBA components.

EJB Containers

An EJB container acts as the interface between an enterprise bean and low-level, platform-specific functionality that supports the bean. In essence, the EJB container is an abstraction that manages one or more EJB classes, while making the required services available to EJB classes through standard interfaces as defined in the EJB specification. The container vendor is also free to provide additional services implemented at either the container or the server level. An EJB client never accesses a bean directly. Any bean access is done through the methods of the container-generated classes, which, in turn, invoke the bean's methods.

Having the container interpose on all bean invocations allows the container to manage transactions, load bean instances, if necessary, and, in general, to do all the wonderful things EJBs do.

Two types of containers exist: session containers that may contain transient, nonpersistent EJBs whose states are not saved and entity containers that contain persistent EJBs whose states are saved between invocations.

The Home Interface and Home Object

Factory methods for locating, creating, and removing instances of EJB classes are defined in the home interface. The home object is the implementation of the home interface. The EJB developer first has to define the home interface for his bean. The EJB container vendor provides tools that automatically generate the implementation code for the home interface defined by the EJB developer.

The Remote Interface and EJBObject

The remote interface lists the business methods available for the enterprise bean. The EJBObject is the client’s view of the enterprise bean and implements the remote interface. While the enterprise bean developer defines the remote interface, the container vendor provides the tools necessary to generate the implementation code for the corresponding EJBObject. Note, however, the EJB container is still responsible for managing the EJBObject. Each time the client invokes the EJBObject’s methods, the EJB container first handles the request before delegating it to the Enterprise Bean.

The Enterprise JavaBean

The real enterprise bean itself is contained within an EJB container and should never be directly accessed by anyone but the container. Although direct access may be possible, this is inadvisable as it breaks the contract between the bean and the container.

The EJB container should mediate all enterprise bean accesses. For this reason, the enterprise bean developer does not implement the remote interface within the enterprise bean itself. The implementation code for the remote interface is generated automatically by tools the container vendor provides, in the form of the EJBObject. This prevents inadvertent direct accesses from clients or other beans.

The EJB Clients

EJB clients locate the specific EJB container that contains the enterprise bean through the Java Naming and Directory Interface (JNDI). They then make use of the EJB container to invoke bean methods. The EJB client only gets a reference to an EJBObject instance and never really gets a reference to the actual Enterprise Bean instance itself. When the client invokes a method, the EJBObject instance receives the request and delegates it to the corresponding bean instance while providing any necessary wrapping functionality.

The client uses the home object to locate, create, or destroy instances of an enterprise Bean. It then uses the EJBObject instance to invoke the business methods of a bean instance.

The EJB Lifecycle

In any enterprise development scenario, numerous complex programming issues are usually involved, which require the involvement of multiple domain experts. Without addressing all these issues and cohesive team-oriented approaches, it is impossible to create successful enterprise applications. To ease enterprise development, the EJB specification assigns responsibilities or roles. The EJB specification also specifies who is responsible for delivering what in an enterprise application that uses EJBs, as shown in Figure 3. Note, the EJB specification does not necessarily preclude the same person from carrying out more than one role.

Figure 3: The lifecycle of a typical enterprise JavaBean

Let’s take a closer look at the different roles the EJB specification defines in greater detail:

EJB Server Provider

The EJB server provider provides an organized application framework in which to run the EJB containers. The EJB server vendor implements and provides access to a JNDI-compatible naming service and a transaction service that is CORBA-OTS-compatible. Note, the EJB server vendor might also act as the EJB container vendor.

EJB Container Provider

The EJB container provider provides software to install an EJB with its supporting classes on an EJB server. The container vendor is also responsible for providing run-time classes that provide the required services to the EJB instances. These include the generation of stub and skeleton classes to provide access to the EJB instance’s home object and EJBObject, installation of references to the home object in a JNDI-accessible namespace. Additionally, it also has to make available a suitable EJBObject implementation that can provide correct proxy services for the enterprise Bean class.

EJB Developer

The EJB developer should have knowledge not only of the EJB specification, but also business needs because she or he is responsible for coding the business logic into server-side components. Basically, the developer implements EJB classes that focus on the business logic using the classes and interfaces defined in the EJB specification.

While the EJB container is responsible for handling all the transaction controls on behalf of the EJB instance, the EJB developer must understands how transactions work. Consequently, the developer is responsible for stipulating the transactional needs of the various methods in the EJB class to the EJB deployer. The EJB specification calls the EJB developer, the enterprise Bean provider.

EJB Deployer

Although the EJB deployer may not be a Java developer or understand the business rules an EJB class implements, he or she should understand the application framework in which the EJB instance runs. Additionally, the deployer should have an in-depth understanding of the characteristics of the run-time server environment, such as database types, its location, and so forth. The deployer is responsible for taking the EJB and all its supporting classes and installing them correctly on the EJB server.

The deployer gets the EJB class requirements from the EJB developer, such as transactional needs, names, and descriptions of the required environment properties, and so forth. The deployer is responsible for making these properties, along with their correct run-time values, available to the EJB class at runtime. The deployer also has to ensure the home object for the EJB class is available in the namespace and is accessible through JNDI. The deployer and the developer must communicate clearly to ensure the EJB class is deployed with the correct deployment attributes.

Application Developer

The application developer writes the client applications using pre-built EJB components. Here, a client is defined generally and can be a Java application, applet, servlet, a CORBA application, or even an ActiveX control connecting through a COM-CORBA bridge.

The application developer can thus plug-in ready-made EJBs without having to develop or test them, or without having any internal knowledge of how to integrate them. This frees the application developer to concentrate on high-level functionality, such as data presentation, without having to worry about how such data is actually obtained. The EJB specification calls the application developer, the application assembler.

Part III

EJB Components

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

The Home Interface and the Home Object

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

Finding the Home Object

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

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

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

// get the JNDI naming context

Context initialCtx = new InitialContext ();

// use the context to lookup the EJB Home interface

AccountHome home =(AccountHome)initialCtx.lookup ("com/~gopalan/Account");

// use the Home Interface to create a Session bean object

Account account = home.create (1234, "Athul", 1000671.54d);

Listing 1: Client code to create an EJB

Definition of the Home Interface

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

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

Listing 2: The EJBHome interface definition

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

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

import javax.ejb.*;
import java.rmi.*;
public interface AccountHome extends EJBHome
{
Account create(int accountNo, String customer)
throws CreateException, RemoteException;
Account create(int accountNo, String customer, double startingBalance)throws CreateException, RemoteException;
Account findByPrimaryKey(AccountPK accountNo)
throws FinderException, RemoteException;
}

Listing 3: The AccountHome interface definition

The Remote Interface

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

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

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

import javax.ejb.*;
import java.rmi.*;
public interface Account extends EJBObject
{
void credit (double amount) throws RemoteException;
void debit (double amount) throws RemoteException;
double getBalance () throws RemoteException;
}

Listing 4: The Account Remote interface definition

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

Entity and Session Beans

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

Entity beans—These beans are generally used to model a business entity.
Session beans—These are more general purpose server-side beans.
Figure 5 illustrates a high-level view of an EJB environment with session and entity enterprise beans.

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

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

Entity Beans

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

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

Persistence in entity beans is of two types:

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

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

To summarize, every entity bean has the following characteristics:

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

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

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

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

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

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

Session EJBs execute on behalf of a single client. A session bean instance is an extension of the client that creates it.
Session beans may be transaction-aware.
Session beans can update data in an underlying database.
Session beans are relatively short-lived. The lifetime of stateless session beans is limited to that of their client.
Session beans may be destroyed when the EJB server crashes. The client has to establish connection with a new session bean object to resume any computation.
Session beans do not represent data that must be stored in a database.
Every session bean can read and update a database on behalf of the client. Its fields may contain conversational state on behalf of the client. The state describes the conversation represented by a specific client/instance pair. Within a transaction, some of this data may be cached in the bean.

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

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

Session Bean
Entity Bean

The data members of the session bean contain conversational state.
The data members of the entity bean represent actual data in the domain model.

A session bean may handle database access for a single client.
Entity beans share database access for multiple clients.

Because session beans are about a conversation with a single client, session beans are allowed to store per-client state information..
Because entity beans are shared between multiple clients, they do not allow storage of per-client state information.

The relationship between a session bean and its client is one-to-one.
The relationship between an entity bean and a row in the domain model is one-to-one.

The life of the session bean is limited to the life of its client.
An entity bean persists as long as the data exists in the database.

Session beans can be transaction aware.
Entity beans are transactional.
Session beans do not survive server crashes.
Entity beans survive server crashes.

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

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

Figure 4: Major components of the EJB architecture

The Home Interface and the Home Object

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

Finding the Home Object

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

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

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

// get the JNDI naming context

Context initialCtx = new InitialContext ();

// use the context to lookup the EJB Home interface

AccountHome home =(AccountHome)initialCtx.lookup ("com/~gopalan/Account");

// use the Home Interface to create a Session bean object

Account account = home.create (1234, "Athul", 1000671.54d);

Listing 1: Client code to create an EJB

Definition of the Home Interface

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

public interface javax.ejb.EJBHome extends Remote {

public abstract void remove (Handle handle)

throws RemoteException, RemoveException;

public abstract void remove (Object primaryKey)

throws RemoteException,RemoveException;

public abstract EJBMetaData getEJBMetaData ()

throws RemoteException;

}

Listing 2: The EJBHome interface definition

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

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

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



public interface AccountHome extends EJBHome {

Account create(int accountNo, String customer)

throws CreateException, RemoteException;


Account create(int accountNo, String customer, double startingBalance)

throws CreateException, RemoteException;


Account findByPrimaryKey(AccountPK accountNo)

throws FinderException, RemoteException;

}

Listing 3: The AccountHome interface definition

The Remote Interface

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

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

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

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



public interface Account extends EJBObject {

void credit (double amount) throws RemoteException;

void debit (double amount) throws RemoteException;

double getBalance () throws RemoteException;

}

Listing 4: The Account Remote interface definition

The EJBObject

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

Entity and Session Beans

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

Entity beans—These beans are generally used to model a business entity.
Session beans—These are more general purpose server-side beans.
Figure 5 illustrates a high-level view of an EJB environment with session and entity enterprise beans.




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

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

Entity Beans

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

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

Persistence in entity beans is of two types:

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

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

To summarize, every entity bean has the following characteristics:

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

No comments: