Skip to main content

skip to main content

developerWorks  >  Java technology  >

What are Enterprise JavaBeans components?: Part 2: EJB programming model

developerWorks
Document options

Document options requiring JavaScript are not displayed


Rate this page

Help us improve this content


Level: Introductory

Ken Nordby (nordby@us.ibm.com), Software Engineer, IBM

18 Jul 2000

Part 2 of this article explains the role of the Java interfaces and classes that are needed to create an Enterprise JavaBean component. In addition to coding the bean class itself, EJB developers must define a home interface and a remote interface for the bean. Implementation classes for these interfaces are typically generated by the container, so deploying an EJB component is a cooperative effort between the developer and the EJB container. Part 2 also differentiates the two primary types of enterprise beans, session beans and entity beans, and describes the relationship between the EJB container and the EJB server.

Three key characteristics of the programming model for enterprise beans are object-orientation, object distribution, and use of proxy objects. The programming model is inherently object-oriented, since it uses Java technology. The model is also distributed, meaning that beans are theoretically location-transparent. According to the Enterprise JavaBeans (EJB) specification, "The actual locations of an EJB class and EJB container are, in general, transparent to the client." Proxy objects are used when a client wants to access an EJB component. The bean itself is not accessible to the client; access to bean methods is provided by helper classes.

Interfaces, delegation, and proxies

When Java programmers write an Enterprise JavaBeans component, the class they create must implement an EJB interface, and it must contain a method named ejbCreate(). An EJB interface -- for example, the SessionBean interface -- specifies methods that include the following:

  • ejbActivate()
  • ejbPassivate()
  • ejbRemove()
  • setSessionContext()

The ejbActivate() and ejbPassivate() methods notify a bean that the container component, which manages the bean, is switching the bean's state between active and passive (usually this refers to in-memory vs. swapped to disk). The ejbRemove() method lets the bean know that it is being removed from the container. The setSessionContext() method associates the bean with a context object that facilitates communication between the bean and its container.

Don't miss the rest of this series
Part 1, "The history and goals of EJB architecture" (June 2000)

Part 3, "Deploying and using Enterprise JavaBeans components" (July 2000)

The ejbCreate() method does not create an enterprise bean from scratch. When a client wants to make a new enterprise bean, the bean's container calls the newInstance() method of the bean's class to instantiate a new bean object. The container then calls the setSessionContext() method to establish a context object for communicating with the bean. Finally the container calls the ejbCreate() method in the new bean. Methods like ejbCreate(), ejbActivate(), and ejbPassivate() are sometimes referred to as object life cycle methods, and are distinguished from business logic methods.

When a developer designs a new EJB component, writing the code that makes up the enterprise bean class is not enough in itself. The EJB programmer must also write two Java interfaces that will be used by helper classes. These mandatory interfaces must extend the standard EJBObject and EJBHome interfaces, which are extensions of the java.rmi.Remote marker interface. The interface that extends the standard EJBObject interface, referred to as the enterprise bean's remote interface, specifies the business methods that are defined in the bean itself. When an application invokes a business method on an enterprise bean, the application does not access the bean itself. The method invocation is actually routed to the object that implements the extension of the EJBObject interface. This practice is referred to as delegation, and is a design point in the EJB architecture:

"A client never accesses instances of the enterprise bean's class directly. A client always uses the enterprise bean's remote interface to access an enterprise bean's instance. The class that implements the enterprise bean's remote interface is provided by the container. The distributed objects that this class implements are called EJB objects." (Enterprise JavaBeans Specification 1.0)

A bean's extension of the EJBObject interface is referred to as its remote interface, and the objects that implement the remote interface are the EJB objects.

An enterprise bean must also have a home interface. This interface is an extension of the standard EJBHome interface. Objects that implement a bean's home interface are referred to as home objects. A home object contains a create() method that is invoked by applications that must create a bean instance. The create() method in the home object creates a new EJB object. It does not directly create a new enterprise bean instance because direct access to a bean is not permitted.

EJB objects and home objects serve as proxies for bean objects because they receive method calls on behalf of the bean. The EJB object acts as a proxy primarily for bean business methods; the home object acts as proxy primarily for bean life cycle methods.

Exercising the create() method for an EJB component does not necessarily instantiate a new bean. The container determines how best to satisfy the create request, and for some types of beans it can reuse an existing instance:

"Clients use the create and remove methods on the home interface of a session bean. Although the client thinks it is controlling the life cycle of an EJB instance, the container is handling the create and remove calls without necessarily creating and removing an EJB instance. There is no fixed mapping between clients and... instances. The container simply delegates client work to any available instance that is method-ready." (Enterprise JavaBeans Specification 1.0)

Creation of new bean instances is under the control of the container, and can be asynchronous with respect to issuance of create() methods by the client.

When creating an EJB component, a developer is responsible for defining the EJBObject interface and the EJBHome interface, but does not need to code the classes that implement these interfaces. The EJB container software component creates these classes automatically.

The following code fragment illustrates how a client application might use an enterprise bean called CartBean to do online shopping:

CartHome cartHome = javax.rmi.PortableRemoteObject.narrow(
initialContext.lookup("applications/shopping_cart"), CartHome.class);
Cart cart = cartHome.create();
cart.addItem(item29);
cart.addItem(item67);
cart.addItem(item91);
cart.purchase();
cart.remove();

CartHome is the class that implements the home interface (the extension of the EJBHome interface). Cart is the class that implements the remote interface (the extension of the EJBObject interface). When the client invokes application methods such as addItem() and purchase(), they are invoked on the cart object, which in turn delegates execution of these methods to the bean itself. The functionality of the enterprise bean is available through its proxy EJB object, cart. What happens if multiple clients access the cart bean at the same time? Enterprise bean developers do not have to write code to support concurrent access. Concurrency is supported by the EJB container.

The following figure illustrates the relationship of EJB objects:

Relationship of EJB objects



Back to top


Servers and containers

The EJB architecture includes the concepts of EJB server and EJB container. The EJB server acts as a component execution system as described in the EJB white paper:

"The Enterprise JavaBeans specification defines a standard model for a Java application server that supports complete portability. Any vendor can use the model to implement support for Enterprise JavaBeans components. Systems, such as TP monitors, CORBA runtime systems, COM runtime systems, database systems, Web server systems, or other server-based runtime systems can be adapted to support portable Enterprise JavaBeans components." (Thomas, Enterprise JavaBeans Technology: Server Component Model for the Java Platform)

An EJB server provides the operational environment for applications using EJB components, and delivers all necessary services to support the EJB architecture. There is no prescribed way to package EJB server software. One approach is to include it as a functional enhancement in an application server, which is the approach taken with the IBM WebSphere Application Server, Advanced Edition, Version 2.0.

EJB components do not execute directly on top of the EJB server. An intermediate software component referred to as the EJB container runs within the EJB server environment, and in turn provides the operational environment for the beans themselves. EJB containers are completely transparent to EJB applications, but play a critical role in supporting bean operation.

In order for enterprise beans to act as reusable software components, they cannot have built-in dependencies on specific server or platform functionality. Several common types of server-side functionality have been “factored out” of the bean design, with responsibility for this functionality transferred to the container component. For example, containers are intended to take over responsibility for security, concurrency, transactions, swapping to secondary storage, and other services, allowing beans to be free of server dependencies, and to be optimized for business logic rather than services logic.

"An EJB container manages the enterprise beans that are deployed within it. Client applications do not directly interact with an enterprise bean. Instead, the client application interacts with the enterprise bean through two wrapper interfaces that are generated by the container: the EJB Home interface and the EJB Object interface. As the client invokes operations using the wrapper interfaces, the container intercepts each method call and inserts the management services." (Thomas, Enterprise JavaBeans Technology: Server Component Model for the Java Platform)

It is anticipated that EJB container software typically will be shipped with EJB server software, although the specification allows separation of these components. In addition to providing access to run-time services such as transactions and security, EJB containers are also expected to include a variety of tools necessary to support installation, operation, and management of enterprise beans. For example, tools are required to interpret the contents of EJB jar files, to generate database access for container-provided persistence, to monitor behavior of running beans, and to implement security.



Back to top


Bean flavors

EJB components are divided into two main categories -- session beans and entity beans. These categories can be further subdivided depending on how beans handle state, transactions, and persistence. A session bean typically has the following attributes:

  • Executes on behalf of a single client
  • Can be transactional
  • Can update data in a shared database
  • Is relatively short-lived
  • Lifetime typically is that of the client
  • Any persistent data is managed by the bean
  • Can be removed at the discretion of the container
  • Is removed if the EJB server fails

An entity bean typically has the following attributes:

  • Represents data in a database
  • Is transactional
  • Allows shared access from multiple users
  • Can be long-lived
  • Persistent data can be managed by the container
  • Survives EJB server failures

The EJB specification describes session and entity beans as follows:

"For a client, a session enterprise bean is a non-persistent object that implements some business logic running on the server. One way to think of a session object is that a session object is a logical extension of the client program that runs on the server. A session object is not shared among multiple clients.
"For a client, an entity enterprise bean is a persistent object that represents an object view of an entity stored in persistent storage (for example, in a database) or an entity that is implemented by an existing enterprise application." (Enterprise JavaBeans Specification 1.0)

As a rule of thumb, session beans represent operations that retrieve or store data to satisfy user requests, while entity beans represent data assets that are accessed to satisfy user requests.

Session beans

The simplest kind of Enterprise JavaBeans component is a stateless session bean. Because these beans have no state to distinguish them, all instances are identical. The container manages the life cycle of stateless session beans by creating sufficient numbers to satisfy the client workload and removing them when they are not needed. Passivation, which is the writing of an idle bean to disk, is not used for stateless session beans. To invoke a bean, client programs call the standard create() method in the home interface, although this action may not necessarily result in instantiation of a new bean instance. The container can elect to send client requests to existing objects. Conversely, the container can create new instances when it chooses, independently of create() methods issued by clients.

The create() call issued on the EJB home object returns a reference to an EJB object representing the enterprise bean. Once a client has an EJB object reference, it can issue business methods on the EJB object, which the container in turn delegates to the bean itself. The container component, which is charged with managing session beans, does not have to infer whether a session bean is stateless or not. Session beans are declared to be stateless or stateful at installation time.

Session beans are stateful if they retain state information between method calls. Stateful session beans can be passivated or written to secondary storage, at the container's discretion, by calling the ejbPassivate() method. The EJB specification does not require containers to use the Java serialization protocol when passivating beans, but they must provide equivalent functionality. When a container determines to swap an inactive session bean back into memory, it deserializes the passive bean and calls the ejbActivate() method. Developers of stateful session beans are responsible to ensure that state data is serializable. Caution is necessary when implementing stateful session beans in a clustered application server environment, because not all servers support synchronization of clustered stateful session beans.

Stateful session beans can be transactional. A bean can control transactions using methods in the javax.transaction.UserTransaction interface such as begin(), commit(), and rollback(), and can receive notifications about transaction status by implementing the javax.ejb.SessionSynchronization interface. The EJB container does not need to infer which beans need transaction support; the UserTransaction interface is made available only to beans marked as transactional at installation time.

Entity beans

Entity beans are architecturally similar to session beans, but rather than supporting user sessions, they provide access to enterprise data. One entity bean can support multiple concurrent users, and the container synchronizes access with transactions. Entity beans also have primary keys that support finder methods in the home object. A client that knows the primary key of an entity bean can obtain an object reference by invoking the findBy PrimaryKey() method on the home object. Unlike session beans, home objects for entity beans have a finder method as well as a create method.

Persistence is an essential attribute of entity beans. The EJB specification allows two forms of entity persistence: bean-managed persistence and container-managed persistence. For an entity bean that represents data in a relational database, bean management of persistence means that database access calls are written directly in the methods of the enterprise bean (using JDBC or SQLJ). This approach is straightforward, but it reduces portability. Container management of persistence means that the bean is free of database calls. The container is informed at installation time about bean data requiring persistence, and the container is responsible for generating code that implements the persistence. This approach allows the bean to be more portable, even to the point of using dissimilar data sources for persistence. However, this approach requires sophisticated functionality in the container.

Entity bean objects are in a ready state when they are associated with an EJB object; otherwise they are considered to be in a pooled state. When a client invokes a method on an EJB object, the container locates the associated entity bean instance if it exists, or transfers an instance from the pooled state. Entity beans in the ready state can receive business method invocations propagated to them from the client by delegation. They can also execute ejbLoad() and ejbStore() methods when requested by the container. The purpose of the load and store methods is to maintain data consistency between the entity bean and the underlying data store.

Entity beans support multiple users with concurrent access to data. The EJB specification declares that maintaining data integrity is the responsibility of the container:

"The enterprise bean developer does not have to worry about concurrent access from multiple transactions when writing the business methods. The enterprise bean developer writes the methods assuming that the container will ensure appropriate synchronization for entity beans that are accessed concurrently from multiple transactions." (Enterprise JavaBeans Specification 1.0)

The container typically accomplishes this either by locking the data in the database and serializing accesses, or by creating multiple instances of the entity bean and allowing concurrency control in the underlying data store to manage the accesses.



Back to top


Coming up in Part 3

Part 3 of "What are Enterprise JavaBeans components?" will discuss the special process of deployment for installing EJB components. It will also address whether CORBA is a competitor to EJB components. (The answer is no -- see how EJB technology complements CORBA.) And finally, see a scenario using an EJB-based three-tier programming model.



Resources



About the author

Ken Nordby is a software engineer in the IBM software development lab at Research Triangle Park, North Carolina. As a member of the SWG Product Affinity Services operations team, Ken worked with IBMers who develop and consult for the IBM WebSphere Application Server, IBM's implementation of Enterprise JavaBeans. Ken can be reached at nordby@us.ibm.com.




Rate this page


Please take a moment to complete this form to help us better serve you.



 


 


Not
useful
Extremely
useful
 


Share this....

digg Digg this story del.icio.us del.icio.us Slashdot Slashdot it!



Back to top