The state of Java middleware, Part 2: Enterprise JavaBeans

Learn how Enterprise JavaBeans fits into your enterprise -- and which tools support EJB

Last month JavaWorld published the first article in this two-part series, covering the state of Java middleware. The first article provided an overview of the many features offered and promised by Java middleware; this article focuses specifically on one of those features: Enterprise JavaBeans (EJB).

By now you've probably heard about EJB, read articles about it, and possibly even written a few enterprise beans yourself. However, if you're like many people out there, you might not understand the big picture -- despite the fact that working with EJB is supposed to be extremely simple. Here's a list of questions many developers new to EJB struggle with:

  • What are all the features of EJB?
  • What tools are available today that support EJB?
  • When should I use session beans versus entity beans?
  • When to use a stateful session bean versus a statelessone?
  • What are the dos and don'ts of EJB development?
  • How does EJB relate to JDBC 2.0 (Java Database Connectivity) and the transaction management APIs?
  • How does EJB's security work?
  • How do complex joins in an existing relational database work with entity bean mapping?

This article addresses these and other common concerns about EJB. It includes examples of how some vendors provide EJB support. Moreover, this article addresses the following key issues:

  • Whydo we need EJB?
  • Whowill support EJB?
  • Whatexactly is EJB?
  • Howdo you develop, deploy, and manage EJB?
  • Howdo you integrate EJB with existing systems?
  • Wheredoes EJB go from here?

In short, this article describes the current state of EJB and the Java middleware (tools) that support it. Rather than focus on in-depth coding examples, I devote attention to the more challenging aspects of working with EJB: the design issues and tools selection. To learn more about nitty-gritty programming with EJB, see the JavaWorld articles in the Resources section below. Furthermore, EJB programming (developing enterprise beans), in my opinion, is the easy part (as Sun intended it to be); design issues and tools selection are the more challenging aspects of working with EJB.

Note that throughout this article I use the terms Java middleware, application servers, and EJB servers somewhat interchangeably. Marketeers, authors of the EJB (or CORBA/DCOM) specification, and niche developers may see many distinctions among these terms, but for the purpose of this article they all mean the same thing.

Note also that this article is jam-packed with information on EJB. While it may seem overwhelming, don't be discouraged: EJB developers typically don't have to deal with all the issues discussed here. In fact, the EJB specifications define several roles and responsibilities that can be handled by either one person or several people, depending on the size of your project. Nevertheless, an understanding of the big picture is essential. And remember, developing enterprise beans is actually extremely simple.

Why do we need EJB?

Ever since the Web began to make the Internet popular and useful for almost everyone (not just the government and students), new Net technologies (Internet, intranet and extranet) have emerged from all directions and organizations. It is now close to impossible to keep up with these technologies at the speed they're being introduced.

So, why should we add EJB to this list of technologies? Well, there are various reasons, but before we look at the reasons for EJB, let's look at several reasons why we need middleware or, more specifically, application servers.

Glue between clients and servers

On the front end, there are many different types of clients (desktops/browsers, PDAs, Web phones, NCs/thin clients, different platforms). On the back end, there are many types of platforms (Unix, Windows, Mac) and data repositories (RDBMS, ODBMS, Mainframe). Java middleware connects the two (see Figure 1). In other words, business logic can be implemented as reusable components in the middle tier, thereby providing access for a variety of clients to all types of data on the back end.

Figure 1. What an application server provides

Scalability and standards-based technologies

The original HTML and/or CGI solution isn't scalable and APIs such as Netscape's NSAPI and Microsoft's ISAPI are proprietary. Most app servers provide standards-based technologies that scale well. Additionally, these products typically provide features such as resource pooling, fault-tolerance, security, management, and other built-in bells and whistles.

One-stop shop

Many app servers are a one-stop shop, that is, they support all the necessary protocols to provide a complete application development solution. Take for example, BEA's WebLogic application server, which provides support for HTTP, RMI, EJB, Servlets, JNDI, JDBC, and other protocols, or Oracle's Application Server, which supports HTTP, CORBA/IIOP, and more. This frees you from having to run multiple servers (e.g., a Web server, a CORBA ORB, and an RMI server).

Now that we've looked why application servers are needed for Net development, let's look at why there's a need for EJB.


EJB increases productivity for developers because they need not worry about low-level system programming (such as connection pooling, security, transaction management, state management, persistence, number of clients, and multithreading); they simply concentrate on writing the business logic and develop the enterprise bean almost as if it will be used by a single client.

Open server-side component architecture

In the past two or more decades, most server-based products have used the vendor's proprietary APIs, so not many off-the-shelf, plug-and-play components have been available, except from the vendors themselves. EJB changes this by providing portability across platforms and vendors. Because EJB sets a clear path for application vendors, all must provide the same minimal functionality in their server products, opening the flood gates for component builders to build off-the-shelf server-side components, not just client-side GUI components. For example, an off-the-shelf enterprise bean could handle functions such as credit card validation.

Object-oriented programming on the server

Thanks to Java's object-oriented roots and the EJB component model, organizations can more easily create and use reusable components, and thus spend less time writing code. One factor helping this reusability is that the logic and data are packaged together in objects. Additionally, EJB containers can translate relational data into objects automatically. This eliminates the distinction between accessing data from a database versus from any other object.

Java in the middle tier

EJB brings all Java features (such as security, directory services, and serialization) to the middle tier. In general, EJB drives forward Sun's layer-and-leverage philosophy, which calls for portability and leveraging existing enterprise investments.

Support for other languages and CORBA

EJB provides support for other languages and CORBA because the middleware vendor, not the enterprise bean developer, handles the communication protocol issues. For example, the default wire protocol for EJB is RMI; however, the EJB 1.0 specifications also provide mapping to CORBA. Furthermore, a vendor can use any distributed protocol to support many types of clients (COM/DCOM for example).

Who will support EJB?

EJB by itself isn't a product. Rather, it's a specification. One of the key objectives of EJB is portability across platforms and vendor products. Several vendors already support EJB or have announced plans to support it in future versions of existing products; additionally, Sun intends to provide a reference implementation of EJB by the second quarter of this year. Table 1 shows a partial list of vendors that have endorsed EJB:

Vendor Product
BEA Systems WebLogic Application Server
Bluestone Sapphire/Web
Gemstone Gemstone/J
IBM Websphere
Information Builders Parlay Application Server
Inprise Inprise Application Server
Lotus Notes/Domino
Netscape Netscape Application Server (Kiva)
Novera jBusiness
Oracle Oracle Application Server
Persistence PowerTier for EJB
Progress Aptivity, Webspeed
Secant Extreme Enterprise Server for EJB
Silverstream Silverstream Application Server
Sun NetDynamics
Sybase Enterprise Application Server
Valto Systems Ejipt
Wall Data Cyberprise Server

Table 1. EJB endorsers

What exactly is EJB?

EJB is part of Sun's Java Platform for the Enterprise (JPE) initiative. JavaBeans introduced a standard way of developing and using Java components on the client side. Similarly, EJB serves as the Java component architecture for the server side.

EJB enables software developers to build server-side, reusable business objects (enterprise beans). However, EJB takes the notion of reusable objects one step further by providing for attribute-based programming to dynamically define lifecycle, transaction, security, and persistence behavior in EJB applications. For example, using attribute-based techniques, the same enterprise bean (in its binary form -- that is, class and/or Java archive [JAR] files) can exhibit different transactional behavior in different applications. Additionally, the method of persisting an enterprise bean can be altered during deployment without ever having to recode the enterprise bean. For example, an entity bean could use a relational database for its persistence or CICS; the enterprise bean developer never needs to know.

To provide a more concrete picture of what EJB is, let's look at the following topics borrowed from the EJB 1.0 specifications:

  • Goals
  • Features
  • Roles and responsibilities
  • Programming restrictions


The EJB 1.0 specifications define certain goals for Java middleware vendors who will implement this standard. The following are a few of these goals:

  • Standard distributed component architecture for Java
  • Portability across platforms and vendors
  • Increased productivity via simplicity (developer doesn't worry about state management, multithreading, network connections and protocols, resource pooling, and so on)
  • Compatibility with other programming languages and CORBA
  • Address development, deployment, and management
  • Compatibility with existing enterprise infrastructure and/or platform investments


To fulfill the above goals, EJB provides several features that make this distributed component architecture so appealing. Table 2 provides a snapshot of these features (more details on each feature are provided further in the article).


Supported through

Component model
  • Session beans
  • Entity beans
Object Persistence
  • Entity beans (EJB containers)
Transaction management
  • javax.jts.UserTransaction
  • Can be vendor-proprietary
Exception handling
  • Client- and server-side
  • Security-related methods in javax.ejb.EJBContext
  • Deployment descriptor properties (Java security ACLs, RunAs properties)
Naming and directory service
  • Java Naming and Directory Interface (JNDI)
Wire protocol
  • IIOP (via CORBA mapping)
  • (Any other distributed protocol)
Support for CORBA
  • CORBA mapping (ejb.idl)
  • CORBA services
Attribute-based programming
  • Deployment descriptor file
  • EJB JAR file
Table 2. EJB feature list

Three enterprise bean types -- which to use?

EJB provides three enterprise bean types: stateless session beans, stateful session beans, and entity beans.

Stateless session beansare intended to be simple and lightweight, that is, easy to develop with low runtime resource requirements on the server for scalability components. Any state, if required, is maintained by the client, thereby making the server highly scalable. Since no state is maintained in this enterprise bean type, stateless session beans aren't tied to any specific client, hence any available instance of a stateless session bean can be used to service a client.

Stateful session beansprovide easy and transparent state management on the server side. Because state is maintained in this enterprise bean type, the app server manages client-bean pairs. In other words, each instance of a given enterprise bean is created on behalf of a client and is intended to be a private resource to that client (although it could be shared across clients using the enterprise bean instance's handle). In essence, a stateful session bean is a logical extension of the client, except some of the client's load is distributed between itself and the enterprise bean on the server. Any conversational state-related data in the object's variables doesn't survive a server shutdown or crash, although a vendor could provide an enhanced implementation to make shutdowns and crashes transparent to the client by maintaining the enterprise bean's state. Stateful session beans can access persistent resources (such as databases and files) on behalf of the client, but unlike entity beans, they don't actually represent the data. For example, a session bean could access data via JDBC or an entity bean.

Entity beansare persistent objects and represent an object view of data stored in permanent storage. To better understand what an entity bean is, think of it as a row in a relational database. Along those lines, an entity bean can be created, found, and removed -- using the create(), findxxx, and remove() methods -- just as a database row can be INSERTed, SELECTed, and DELETEd in an SQL database. An entity bean lives in an EJB container in much the same way a record lives in a database. Herein lies the beauty of entity beans; a vendor can provide EJB containers for various data sources (such as Oracle or CICS) and the enterprise bean developer never needs to know. Unlike stateful session beans, entity beans can be accessed by multiple clients concurrently -- the concurrency is managed by the EJB container. Since entity beans provide an object view of the data, the actual data they map to in the permanent store may either be created via the entity bean's create()method or exist beforehand in the permanent store (for example, using an SQL database's INSERT command). On the flip side, entity beans can be removed, either using the entity bean's remove() method or by deleting the bean directly from the permanent store. The find() methods can be used to return either a single object or collection of objects.

Deciding which type of enterprise bean to use is more an issue of design than of development. Here are two general rules of thumb:

  1. Use entity beans instead of session beans if you don't want to embed database calls in your enterprise bean classes but you do want to take complete advantage of such EJB features as automatic transaction management, resource pooling, and container-managed persistence. Also, think of a session bean as a logical, short-lived extension to the client -- the object disappears as soon as either the client or the server shuts down. Think of entity beans as persistent, long-lived objects that can be shared by multiple clients, perhaps for years (similar to data in a database).

  2. If you choose to use session beans, picking between statelessand stateful beans means deciding how much load to put on the client versus the server. In other words, if you maintain state on the server (that is, a stateful session bean), the server will be taxed, whereas a stateless bean minimizes server load and instead lets the client manage state.

Despite their differences, session and entity beans do share the following characteristics:

  • A handle (javax.ejb.Handle) can be obtained to a enterprise bean's instance using the getHandle() method

  • An enterprise bean can be customized at deployment time by editing its environment properties

  • Instances of an enterprise bean are created and managed at runtime by the application server

  • Certain attributes of the enterprise bean, such as transaction mode and security, can be manipulated at deployment time by using the EJB server deployment tools

  • Both can be transaction-aware

  • Both can be created and deleted (destroyed) via the create()and remove() methods using their home interface. The create() methods are used to initialize the object's fields.

For a big-picture look at what we've learned about EJB so far, Figure 2 portrays a snapshot of a hypothetical EJB server environment.

In particular, please note the following:

  • An EJB Server can have multiple containers
  • A container can have multiple beans of different types
  • An entity bean maps to a row in a database
  • A client can use any type of enterprise beans
  • Stateful session beans are tied to a specific client
  • Stateless session beans are not tied to a specific client; they are instead used from a pool as necessary
  • Entity beans can be shared across clients and accessed concurrently
Figure 2. Interaction across clients, beans, and tiers


One of EJB's key features is built-in persistence, which is provided by entity beans. The persistence can be either bean-managed or container-managed.

For bean-managed persistence, the developer overrides the ejbLoad()and ejbStore() methods and provides the custom code (for example, by using JDBC) to transfer the data from the object's fields to the permanent store and vice versa. While bean-managed persistence provides a lot of flexibility, it ties the entity bean to one method of persistence, such as JDBC, and requires the developer to write and maintain the persistence code. In some cases, however, the developer may have to employ a bean-managed solution (e.g., if an EJB container provider's mapping tools allow mapping of an entity bean to only a single table but the entity bean needs data from multiple tables). Fortunately, many application-server vendors are beginning to bundle object-relational (OR) mapping tools that can handle complex joins and other entity relationships and still provide you with the benefits of container-managed persistence, and third-party OR tools can fill the void if your favorite application server lacks an OR tool. Alternatively, you can use a relational-database view to represent multiple tables and their relationships as one table, but you should be aware that many databases do not support data updating in multiple tables via views.

In a container-managed situation, a container provider (vendor) supplies mapping tools to map the entity bean's fields to the fields in the data store (such as a relational database table's columns). For example, Figure 3 shows Persistence Software Inc.'s PowerTier ObjectBuilder, an object-relational mapping tool. ObjectBuilder automates the mapping of complex beans, including inheritance, aggregation, and association, to relational tables, thus enabling greater developer productivity and more reliable code. (Persistence Software also offers Rational Rose integration for OR mapping and enterprise bean generation.)

Figure 3. Persistence's ObjectBuilder

While the mapping process can be tedious, the advantages of using container-managed persistence outweigh the minor disadvantages. For example, the container provider automatically generates the code to move the data between the entity bean's fields and the data store; for relational database applications, this is an automatic object-relational mapping feature. Additionally, the entity bean can be persisted into a different data source simply by using a different EJB container and remapping the fields. Furthermore, a container provider might optimize the data access by caching data in the containers, so the data store doesn't have to be accessed for every single request. Examples of EJB containers include WebLogic's JDBC- and file-based containers and Information Builder's EJB containers for CICS, 3270, MQ Series, and other legacy database systems.

Transaction management

EJB supports flat transactions, modeled after the CORBA Object Transaction Service (OTS) version 1.1. For transactions, no distinction is made between a session bean and an entity bean except for one subtle difference that allows only stateful-session beans to suspend a user-managed transaction (when using the TX_BEAN_MANAGEDtransaction attribute, discussed below). Additionally, the developer isn't exposed to the complexity of transactions that could potentially be distributed across multiple data sources on multiple platforms -- this responsibility is shifted to the Java middleware (or app server) provider.

Transaction demarcation in an EJB environment can be handled in one of two ways. First, the developer can programmatically control the scope of transaction using the javax.jts.UserTransactioninterface (an app server vendor must provide an implementation for this) at the client or server. Secondly, the app server provider manages the transaction boundaries using the deployment settings for the transaction attribute, which can apply to either the entire enterprise bean or its specific methods. (This method is also known as declarative or attribute-based programming.)

Table 3 provides a list of valid values for the EJB transaction attribute. These values typically can be set for a given enterprise bean using tools provided by the app server vendor.

Attribute value

How enterprise bean is invoked

TX_NOT_SUPPORTED Invoked without a transaction scope.
TX_BEAN_MANAGED An enterprise bean can use the javax.jts.UserTransaction interface to demarcate transaction boundaries. The UserTransaction interface can be obtained using thejavax.ejb.SessionContext.getUserTransaction() method. An instance of a stateless session bean or an entity bean is not allowed to retain an association with a transaction across multiple calls from a client.
TX_REQUIRED If the client is associated with a transaction context, the enterprise bean is invoked in the same context, otherwise the container starts a new transaction before invoking a method on the enterprise bean and commits the transaction upon returning from the method.
TX_SUPPORTS Invoked in the client's transaction scope, if it has one. Otherwise, invoked without a transaction context.
TX_REQUIRES_NEW Always invoked in a new transaction.
TX_MANDATORY Always invoked in the scope of the client's transaction. If the client does not have one, javax.transaction.TransactionRequiredExceptionis thrown to the client.

Table 3. Valid values for transaction attribute

EJB also provides support for transaction isolation levels, a concept that allows changes made by one transaction to be visible to other transactions. The valid values for EJB isolation levels, also set in the deployment descriptor (typically using vendor tools), are as follows:


For session beans and entity beans with bean-managed persistence, the specified isolation level is set in the database connection (for example, the JDBC isolation levels). For container-managed entity beans, the vendor must provide this functionality.

Relationship to JDBC 2.0

JDBC 2.0 introduces a standard extensions API (javax.sql package) that includes support for distributed transactions in addition to features such as resource pooling and rowsets. The support for distributed transactions lets developers write enterprise beans that are transactional across multiple DBMS servers.

To provide a standard way of supporting distributed transactions in Java, JDBC ties into the Java Transaction API (JTA) and Java Transaction Service (JTS). The JTS API provides the necessary interfaces and classes for transaction management in Java. It can, for example, attach a JDBC driver to an external transaction manager using the standard X/Open XA interface. (JDBC 2.0 introduces the javax.sql.XADataSource and javax.sql.XAConnectioninterfaces, which any drivers supporting distributed transactions must implement if the driver vendor claims to support the standard JDBC extensions.)

Exception handling

The EJB 1.0 specifications define two types of exceptions: application-level and system-level. Since a client accesses an enterprise bean's methods via its home and remote interfaces, all methods defined in these interfaces must include a java.rmi.RemoteException. When a RemoteExeptionis thrown, a client can assume it is a system-level failure. All other exceptions, including the javax.ejb.CreateException, javax.ejb.RemoveException, and javax.ejb.FindException, are considered application-level failures.

In relation to transactions, a client can assume that a transaction was rolled back if a javax.jts.TransactionRolledbackExceptionis thrown. (Note: The javax.ejb.SessionContext.getRollbackOnly() method can also be called to test whether or not a transaction was rolled back using the setRollbackOnly() method.)


EJB uses the class to describe users and/or roles. The app server (or EJB container) actually performs the mapping, usually in a platform-specific way, and provides this information to the enterprise bean instance via the getCallerIdentity and isCallerInRole(Identity ident)methods in the javax.ejb.EJBContextclass.

EJB security uses access control lists (ACLs) in the deployment descriptor to manage security on behalf of the enterprise bean. EJB also provides attributes, RunAsMode and RunAsIdentity, to define the security Identity to be associated with the execution of methods in the enterprise bean and for any calls to other resource managers (such as JDBC). The valid values for these attributes are SPECIFIED_IDENTITY, CLIENT_IDENTITY, and SYSTEM_IDENTITY (privileged account).

Note that the class was deprecated in Java 2 (aka JDK 1.2). However, the EJB 1.0 specifications and the EJB APIs still refer to this class. Hopefully, the next release of the EJB specifications (which most likely will be EJB 1.1, due June of 1999) will rectify the situation.

Naming and directory service

EJB uses the Java Naming and Directory Interface (JNDI) for its naming service. In other words, a client looks up an EJB's home interface using JNDI. It is the container's responsibility to make the enterprise bean's classes available to the client via JNDI.

Wire protocol

The EJB specifications by default specify Java RMI Protocol (JRMP) as the default protocol for invoking enterprise beans over the network. Additionally, the specifications provide CORBA/IIOP mapping so CORBA clients can invoke enterprise beans. However, EJB isn't limited to using the JRMP and IIOP wire protocols. In fact, EJB can use any wire protocol (such as HTTP or DCOM) to support a variety of client types. Either way, the developer doesn't have to worry about the protocol as EJB vendors handle the low-level details.

Figure 4 shows the various ways enterprise beans can be accessed; for example, the following sample architecture patterns are depicted in Figure 4:

  • An HTML front end can invoke a servlet that in turn invokes the enterprise bean
  • A Java applet or standalone application can invoke the enterprise bean directly
  • A Visual Basic app can use CORBA or the ActiveX bridge to invoke the enterprise bean
Figure 4. Sample EJB-based architecture patterns and corresponding protocols

Additionally, Java middleware could provide support for other protocols, such as DCOM or HTTP, to invoke enterprise beans.

While the default wire protocol for EJB is the Java RMI Protocol, the EJB 1.0 specification defines a CORBA mapping. Essentially, this is accomplished via the IDL files (such as ejb.idl) provided for the EJB classes and interfaces combined with an application-specific IDL for the bean-specific classes and interfaces.

The mapping for CORBA also covers propagation of the transaction, naming, and security contexts as defined by the CORBA Object Services protocols.

Attribute-based development

EJB enhances a developer's productivity not only by providing a simple server-side component architecture but also by introducing declarative,or attribute-based programming. For example, attributes for transactions, isolation levels, security, and mapping to EJB-container data sources all can be handled at deployment time. Hence, developers don't have to worry about these low-level details when developing components; they can instead concentrate wholly on the business logic.


Enterprise beans are deployed via a JAR file, which provides a nice, neat way to include the following required and optional files:

  • The enterprise beans class files (home interface, remote interface, and actual enterprise bean)

  • A deployment descriptor for each enterprise bean. A deployment descriptor is a serialized instance of a javax.ejb.deployment.EntityDescriptoror javax.ejb.deployment.SessionDescriptorobject

  • A manifest file that lists the names of the deployment descriptor files and also indicates which ones are enterprise beans. The format of this file looks something like this:

    Name: divya/infoBookServer.ser Enterprise-Bean: True
    Name: xyz/QuoteServer.ser Enterprise-Bean: True
  • Environment properties for the enterprise bean (typically entered using vendor tools)

Roles and responsibilities

Sun's EJB 1.0 specification defines six different roles involved in development and deployment of EJB (see Table 4). Of course, these roles vary based on the size of your project and/or company. For example, in a small project, the same person could be the enterprise bean provider, application assembler, deployer, and system administrator. Similarly, one vendor could be both the EJB server and the container provider (for example, Information Builders includes several EJB containers with its EJB-compliant application server).

Role Responsibilities
Enterprise bean provider
  • Classes and interfaces
  • Environment properties
  • Deployment descriptor
  • Manifest file
  • EJB packaging (JAR file)
Application assembler
  • Brings all tiers together (client, GUI, servlets, and so on)
  • Uses container tools to map enterprise bean to container (if needed)
  • Modifies security attributes (if needed)
  • Enterprise bean's properties (if needed)
EJB server provider
  • Could be OS, middleware, or database vendor
  • Provides container for session beans
  • Possibly provides containers for entity beans or publishes its low-level interfaces to allow third-party plug-in containers
EJB container provider
  • Responsible for persistence of entity beans
  • Mapping Tools for entity beans (for example, object/relational mapping)
  • Generates code to move data from entity bean instance variables to secondary storage
  • Provides tools to manage container and beans running in that container
System administrator
  • Monitors system
  • Fine-tunes (if needed)

Table 4. Roles and responsibilities

Programming restrictions

Below is a list of restrictions defined in the EJB 1.0 specifications that will generally be enforced by the application server vendor.

  • An enterprise bean is not allowed to start new threads, nor to terminate the running thread.
  • An enterprise bean is not allowed to use read/write static fields. Using read-only static fields is allowed. Therefore, all static fields must be declared as final.
  • An enterprise bean is not allowed to use thread synchronization primitives.
  • An enterprise bean is not allowed to use the calls to an underlying transaction manager directly. The only exceptions are enterprise beans with the TX_BEAN_MANAGED transaction attribute, which are allowed to use the javax.jts.UserTransaction interface to demarcate transactions.
  • An enterprise bean is not allowed to change its Any such attempt will result in the being thrown.
  • A transaction-enabled enterprise bean using JDBC is not allowed to use the commit() and rollback() methods. An enterprise bean that is not transaction-enabled is allowed to use the commit() and rollback()methods.

Source: Enterprise JavaBeans 1.0 specification, Sun Microsystems Inc.

How do you develop, deploy, and manage EJB?

Now that we've covered pretty much everything there is know about what EJB is, let's look at how you actually develop enterprise beans.

As I mentioned previously, the intention of this article is to provide you with the big picture of EJB, not a coding tutorial. Accordingly, the following sections provide an overview of what's required to develop EJB and some of the tools available for the job.

In general, developing and deploying enterprise beans includes the following steps:

  1. Develop the enterprise bean (bean classes, home, and remote interfaces)
  2. Deploy the enterprise bean (deployment descriptor, manifest file, environment properties, and JAR)
  3. Assemble the application (deploy and test connectivity on all tiers)
  4. Manage the beans and related pieces

Developing Enterprise JavaBeans

For every enterprise bean, three pieces must be developed: the actual enterprise bean class; its home interface; and its remote Interface. You can develop all three using your favorite text editor. Optionally, you can use an IDE such as Inprise's JBuilder 2, which will generate skeleton code for you.

Figure 5. JBuilder's EBJ wizard
Figure 6. Inprise JBuilder IDE

For example, Figure 5 shows JBuilder's EJB wizard, which prompts you for the package name, class name, and enterprise bean type, then continues to generate a shell for you to work with. Figure 6 shows the code generated by the wizard. Notice the special enterprise bean methods that are generated with empty bodies (such as ejbCreate and ejbRemove).

The enterprise bean class contains business logic methods that will act on behalf of a client. For example, the following sample session bean class provides a method, getLastName(int), to look up and return a person's last name as a java.lang.String based on a numeric (int) social security number:

import javax.ejb.*;
     import java.rmi.*;
     public class PeopleFinderBean
            implements SessionBean
        SessionContext sessionContext;
        public void ejbCreate() throws CreateException, RemoteException {}
        public void setSessionContext(SessionContext sc)
                    throws RemoteException
           sessionContext = sc;
        // Business methods
        public String getLastName(int ssn)
           String lastName = null;
           // Get name from some data source.
           return lastName;

Since the instance of the above bean can exist on a remote machine (and most likely will in an n-tier app), clients don't actually work directly with the instance of the above class. Instead, through JNDI, the client obtains a sort of a remote handle to the actual instance and uses an enterprise bean class's remote interface to invoke its methods. The following is what the above bean class's remote interface would look like:

import javax.ejb.*;
     import java.rmi.*;
     public interface PeopleFinder
            extends EJBObject
        public String getLastName(int ssn) throws RemoteException;

Once the enterprise bean class and its remote interface have been developed, the developer must provide a home interface for the enterprise bean class. The home interface is what the client first obtains through JNDI. Once the home interface has been obtained, the client can use it to create instances of the remote enterprise bean and remove them; for entity beans, the client can use the home interface to find existing beans. An entity bean's home interface can define zero or more create() methods (with different signature types), one for each method of creating an enterprise bean object. The arguments of the create() methods typically are used to initialize the state of the created enterprise bean object. The return type of a create() method is the enterprise bean's remote interface. The home interface for the above enterprise bean might look something like this:

import javax.ejb.*;
     import java.rmi.*;
     public interface PeopleFinderHome
            extends EJBHome
        public PeopleFinder create()
                            throws CreateException, RemoteException;

Notice the naming convention of the enterprise bean class and its home interface. The use of the word bean at the end of the enterprise bean class's name and the word Home at the end of the home interface's name are naming conventions used in the EJB specification, and thus presumably are recommended practice.

Once the beans have been developed and deployed (see below), a client uses JNDI to find the remote bean's home interface, then uses the home interface to create an instance of the remote enterprise bean and simply call its business methods (via its remote interface) as shown here:

// Do one-time, initialization, stuff
     Properties     env = new Properties();
     env.put(Context.PROVIDER_URL,         "t3://localhost:7001");
     env.put(Context.SECURITY_PRINCIPAL,   "system");
     env.put(Context.SECURITY_CREDENTIALS, "letmeout");
     InitialContext ic    = new InitialContext(env);
     // Get enterprise bean's "Home" and "Remote" Interface
     PeopleFinderHome pfh = (PeopleFinderHome)ic.lookup("statefulSession.PeopleFinder");
     PeopleFinder pf = pfh.create();
     // Call enterprise bean's method
     System.out.println("Last name = " + pf.getLastName(111223333));

Table 5 provides an overview of special methods, classes, and interfaces related to the two enterprise bean types, session and entity. For more details on these, refer to the EJB API documentation and specifications. I've merely listed them here to make you aware that they exist.

Enterprise bean type Special methods, classes, and interfaces
  • Methods: ejbRemove, ejbActivate, ejbPassivate, setSessionContext(SessionContext)
  • Classes: SessionContext, Handle, EJBObject, EJBHome
  • Interfaces: SessionBean
  • SessionContext methods: getEJBObject, getCallerIdentity(), getEJBHome(), getEnvironment(), getRollbackOnly(), getUserTransaction(), isCallerInRole(Identity), setRollbackOnly()
  • Methods: ejbActivate(), ejbLoad(), ejbPassivate(), ejbRemove(), ejbStore(), setEntityContext(EntityContext(), unsetEntityContext().
  • Classes: Handle, EJBObject, EJBHome
  • Interfaces: EntityBean
  • EntityContext methods: getPrimaryKey(), getEJBObject, getCallerIdentity(), getEJBHome(), getEnvironment(), getRollbackOnly(), getUserTransaction(), isCallerInRole(Identity), setRollbackOnly()
Table 5. Enterprise bean interfaces and special methods

By now you should have a general understanding of how to develop enterprise beans. The next section discusses how to deploy these beans using your favorite app server product.

Deploying Enterprise JavaBeans

Deploying an enterprise bean generally involves the following five steps:

  1. Create a deployment descriptor file for each enterprise bean. Vendors typically provide graphical tools to help you do this. Note that for entity beans you must specify the containerManagedFieldsdeployment descriptor property to specify the list of instance fields for which the container provider tools must generate access calls.

  2. Provide a manifest file that lists all the deployment descriptors.

  3. Specify the environment properties that an enterprise bean requires at runtime. This is generally done using vendor-specific products.

  4. Bundle the deployment descriptor, manifest file and, enterprise bean classes (bean class, remote interface, home interface) into a JAR file. You can do this using the standard jar or zip utilities or a vendor may provide a graphical tool to help you do this (for example, Symantec Visual Cafe provides an AutoJAR feature and Inprise's JBuilder has a Deployment wizard).

  5. Deploy your bean using your vendor's deployment tools.
Figure 7. WebLogic EJB Deployment Wizard

Figures 7 and 8 show screenshots of sample EJB compliant products available today. Figure 7 shows the WebLogic EJB Deployment wizard, part of BEA's WebLogic Application Server product. The wizard allows you to select a JAR (or deployment descriptor) file, modify the various deployment descriptor attributes (transaction and security for example) and let the tool generate the necessary class files and deploy the enterprise bean component for you. With the ease of tools such as this, the developer simply concentrates on writing the business logic and let the vendor products do the rest.

Figure 8. Gemstone JConsole

Figure 8 shows you Gemstone's J Console, part of its Gemstone/J product. This screenshot shows a file-open dialog box to select the enterprise bean JAR file (as described above) and deploy it. You can use the graphical interface (written in 100 percent pure Java, Swing to be exact) to configure all aspects of your system. This configuration is organized in a logical manner in property pages, as opposed to working with one large text file.

Managing Enterprise JavaBeans

While each vendor provides the same minimal functionality required by the EJB 1.0 specifications for developing enterprise beans, it's in the deployment and management of these components that you begin to see some of the differences between the products. In particular, the management tool (or console) serves as the heart of each application server product.

For example, Figure 9 shows a screenshot of Novera's Management Console, part of the company's jBusiness4 Application Server product. To give you an idea of the features provided by these management tools, consider some of the options available in Novera's Management Console:

  • Configure components, resources, users and groups
  • Realtime monitoring of application servers, components, containers, and clients
  • Ability to set access control permissions for clients, containers, and components
  • Ability to define the number of concurrent users that may execute a specific client or container, and the number of clients or container instances allowed for each user or group
  • View historical and realtime events
Figure 9. Novera Management Console

How do you integrate EJB with existing systems?

New and cool technologies, such as EJB, usually excite IT workers, who typically seek to introduce these newfound technologies into their projects or organizations. However, one of the immediate questions raised is, How do we access our existing systems using the new technology? While many organizations want to use EJB because of its enormous benefits, the obvious issues related to accessing existing data sources need to be addressed.

EJB vendors tackle the data access issue in different ways. Many bundle JDBC drivers for access to databases such as Oracle, Sybase, Informix, and MS SQL Server. Other vendors rely on existing ODBC drivers and presume developers will use the free JDBC-ODBC bridge from Sun to access these data sources from their Java classes. Then there are vendors that go one step further. For example, Parlay from Information Builders is an EJB-based application server with one of the strongest suites of enterprise beans for accessing mainframe CICS and IMS transactions and more than 70 databases (including VSAM and DB2), as well as integrating TN3270 sessions and MQSeries messaging services. Parlay also features an intuitive, drag-and-drop environment called Visual Configurator (see Figure 10) for developing, deploying, and managing strategic Java business applications. Additionally, Parlay is supposed to be available on more than 12 platforms ranging from NT to IBM OS/390. In any case, most of these EJB vendors will likely provide intuitive GUI-based EJB component-mapping tools for the data sources they support, and when and where these tools fall short, systems integration companies can be brought in to fill the gap.

Figure 10. Parlay Application Server's Visual Configurator

Of course, if all else fails, the last resort for data access from Java is to use the Java Native Interface (JNI). In other words, if there are C/C++ libraries provided by a database vendor, Java classes can be written as "wrappers" to access these native libraries in an object-oriented fashion.

Where does EJB go from here?

EJB is a new and promising technology that should be around for a long time to come, given the enormous industry backing it has already received. When the EJB 1.0 specification was released last year, there were mentions of features deferred for release 2.0. Additionally, the CORBA 3 specifications are supposed to include mapping to, and container support for, enterprise beans. In other words, enterprise beans will most likely be treated as CORBA components by object request broker (ORB) products mainly because these two component models are so similar. (It is worth noting, however, that OMG believes CORBA components will be a superset of EJB components.)

Table 6 provides an EJB roadmap for the next 9 to 12 months.

Release name Schedule Features

Expert Group Review: Early 1Q99

Public review: Late 1Q99

Final: 2Q99

Along with the specifications, Sun will produce a reference implementation and a set of compliance tests

Technology preview: 2Q99

Beta: 3Q99

FCS: 4Q99

Tightening of spec requirements for compatibility, XML deployment info
Javits 6 to 9 months after the release of Moscone Connectors to existing systems
Milano 6 to 9 months after the release of Javits Complete definition of entities
Table 6. EJB roadmap (Source: Sun Microsystems Inc.)

I predict we'll see more implementations of JTA for transaction support across multiple data sources. Also, the integration with JDBC 2 will get tighter, thereby providing benefits such as connecting pooling and transaction support in a nonproprietary fashion. Additionally, ORB/IIOP-based vendors will play an important role in EJB servers due to the inherent portability derived from CORBA. If EJB components reach their ultimate potential and become fully successful, they'll be used by sites such as Yahoo!, E*Trade, and Netscape NetCenter to provide services to their customers.


When JavaBeans was introduced in JDK 1.1, it immediately became the de facto GUI component model for Java. With EJB, we now have a server-side component model for Java. Thanks to Enterprise JavaBeans, we may soon see widespread proliferation of off-the-shelf components for the server side, not just for the client side (as we have seen with JavaBeans and ActiveX controls).

Having the same base functionality in all EJB-compliant products protects corporate investments, and we'll soon be seeing better middleware product as a result. There is no proprietary model, which means everyone can concentrate on the extra bells and whistles. Middleware developers will be able to provide us with the next generation of tools, which will be open to all manner of back-end data sources and will increase reusability of components across not only Java clients but also Windows clients and special devices yet to be invented. Speaking of proprietary versus open standards, EJB developers would do well to avoid vendor-specific features whenever possible and instead use the standard EJB APIs, including JNDI, JDBC, Servlets, and JSP.

The EJB and other standard APIs have made significant progress, and Java middleware vendors have also made advances. These tools still need much improvement, however, to ease the development process through GUI tools such as wizards and other integrated features (e.g., simple EJB deployment, JAR file creation, OR mapping, FTP capabilities, remote debugging, and client-server class hierarchy/relationship-type views). Additional improvements are needed to make the EJB environment not only easy to work with but also robust. Such reliability and scalability issues include transparent fault tolerance, load balancing, and clustering.

Most of all, tools vendors will have to simplify their tools and -- absolutely, positively -- standardize their user interfaces to win the votes of those corporations out there that embrace the look and feel of Microsoft products. Microsoft may have the most proprietary products, but Java middleware vendors would do well to adopt the clean, crisp, appealing, and consistent user interface Microsoft applies to its various products (think Outlook, Office, FrontPage, and SQL Server) and thus provide a pleasant experience for developers.

Anil Hemrajaniis a senior consultant at Divya Inc., a consulting firm specializing in Java/Internet software solutions. Anil Hemrajani provides Java/Internet-based architecture, design, and development solutions to Fortune 500 companies, and occasionally writes articles and lectures at conferences. Cliff Berg contributed to this article; he is the VP and CTO of Digital Focus, a leading Java and Internet technology system integrator.

Learn more about this topic

  • Visit Sun's EJB home page for articles, specifications, press releases, and links related to EJB
  • SunWorldarticle on EJB, designed to help readers determine if this technology is right for their companies. See the IT Architectcolumn "Expanding your server-side toolkit with EJB"
  • The Web site provides a complete list of currently available Java application servers and related vendor white papers
  • Download the free EJB Guide from Nova Labs
  • For CORBA-specific information, visit The Object Management Group's Web site
  • Previous EJB features in JavaWorld
  • "Write a session EJB" by Michael Shoffner (Java Step by Step, July 1998)
  • "Enterprise JavaBeansComing soon to a server near you" by Bryan Morgan (Distributed Objects, June 1998)
  • EJB features on the Java Developer Connection
  • "Enterprise JavaBeansWorking with Entity and Session Beans"
  • "An Introduction to Enterprise JavaBeans Technology"

Join the discussion
Be the first to comment on this article. Our Commenting Policies