Working with EJB

Working with EJB

1 The Importance of EJB

As discussed in Section 11.1, the three-tier model (see Figure) consists of the following components:

  • Client: a Web browser or a client application

  • Presentation: a servlet or JSP that handles interaction with the client

  • Business logic: program code for application-specific processes

  • Data store: a database that manages business data

For example, the classes shown in Section 11.5 include business logic, and the servlet shown in Section 11.6 is a component for the presentation.

However, in these classes, the program code for presentation, business logic, and data store is not cleanly separated, as shown in Figure. Furthermore, a process for transaction control, which should be a common service, is written by developers and embedded in the program.

4. A three-tier Web application with embedded processes


When a large-scale Web application is being developed, we developers want to concentrate on business logic, and common services such as transaction control and database connection management should be provided from the middleware that we use. That can reduce the cost of design, development, and management of the Web application.

Java 2 Enterprise Edition (J2EE) and EJB enable such an environment. This section briefly covers J2EE and EJB and compares them with the approaches we showed earlier in this chapter. If you are interested in this topic, many books are available on J2EE and EJB.

J2EE is a set of server-side Java technologies. Before J2EE was available, many vendors provided their own ways to develop large-scale Web applications. J2EE aims to integrate these technologies as a set of standard technologies. J2EE contains Java Servlet, JDBC, EJB, Java Message Service (JMS), Java Naming and Directory Interface (JNDI), Java Transaction API (JTA), Remote Method Invocation (RMI), and other technologies. Many vendors support J2EE and provide J2EE-compliant middleware. For example, IBM's WebSphere 4.0 is a J2EE-compliant application server. EJB plays a key role in these technologies.

Figure shows a three-tier Web application with J2EE/EJB. There are two clear differences from Figure. First, a Web container and EJB container are introduced in Figure. The Web container contains servlets and JSPs. The EJB container contains business logic and provides the following system services:

  • Transaction management

  • Security (only a client that has a permission can execute business logic)

  • Communication with a remote client/EJB

  • Lifecycle (session) management

  • Database connection management

5. A three-tier Web application with J2EE/EJB


Developers can develop EJBs that contain business logic and not have to worry about implementing the services just listed by using standard technologies.

There are two types of EJBs.

  • An entity bean represents a persistent business object. It is associated with a record in a database, and it is possible to automatically store the object values in a table as column data. Entity beans are categorized into two types.

    - Container-Managed Persistence (CMP). In a CMP, the EJB container handles EJB objects' persistence and accesses database. CMP Developers do not have to write a program code for database access. A CMP basically corresponds to a record in a database table; therefore, join processes among multiple tables are required.

    - Bean-Managed Persistence (BMP). A BMP can provide flexibility. A BMP contains a program code for database access. It similar to the code shown in the previous sections, but developers can manage multiple tables.

  • A session bean is used for describing business logic that does not relate to persistent data. There are also two types of section beans.

    - Stateful session bean. A stateful bean can keep the status (instance values) in the interaction between a client and an EJB.

    - Stateless session bean. A stateless bean does not keep the status and can be used for describing business logic that does not require a state control.

The EJB 2.0 specification, published in October 2000, introduces a new type of enterprise bean—the Message Driven Bean (MDB). J2EE 1.2 itself includes JMS so that you can develop asynchronous processing in large-scale Web applications (described in Chapter 12). However, JMS and EJB are not properly integrated in the sense that you cannot access an EJB container via JMS. In J2EE 1.3 (based on EJB 2.0), MDB provides an EJB container with asynchronous processing functions. Messages sent via JMS are dispatched to an MDB object within the EJB container.

2 A Simple EJB

Next, we show a simple example of EJB. Information on J2EE and EJB is available at The Web site provides the EJB 2.0 specification and a comprehensive tutorial.

The following four classes are required to develop an EJB:

  • An EJB bean class that contains business logic

  • A home interface for the EJB container to create the EJB bean object

  • An EJB client that accesses the EJB bean

  • A remote interface for the EJB client to call the methods of the EJB bean

Listing 11.12 shows an entity bean (CMP) that corresponds to a record in the NODE_VALUE_TBL table, shown in Section 11.5.2.

Listing 11.12 A simple entity bean, chap11/
    package chap11;

    import java.util.*;
    import javax.ejb.*;
    import javax.naming.*;
    // This is a CMP bean based on EJB 2.0
    public abstract class NodeValueBean implements EntityBean {

        private EntityContext context;

        // Access methods for persistent fields.
        // EJB container associates each field with
        // column of a table
        public abstract String getNodeId();
        public abstract void setNodeId(String nodeId);

        public abstract String getPathString();
        public abstract void setPathString(String pathString);

        public abstract String getContentString();
        public abstract void setContentString(String contentString);

        public abstract String getDocumentId();
        public abstract void setDocumentId(String documentId);

        // Implements EntityBean methods
        public String ejbCreate (String nodeId,
                           String pathString,
                           String contentString,
                           String documentId)
            throws CreateException {
            return nodeId;

        public void ejbPostCreate (String nodeId,
                             String pathString,
                             String contentString,
                             String documentId)
            throws CreateException {

        public void setEntityContext(EntityContext ctx) {
            context = ctx;

        public void unsetEntityContext() {
            context = null;

        public void ejbRemove() {}
        public void ejbLoad() {}
        public void ejbStore() {}
        public void ejbPassivate() {}
        public void ejbActivate() {}

        // Defining Business methods

        // Suppose NodeValueInfo is a class that contains column data
        public NodeValueInfo getNodeValueInfo() {
        return new NodeValueInfo(getNodeId(),

        public void updateContent(String content) {

You might be surprised that this program does not contain any program code for database access. There are not even any instance variables that represent column names (which is a new feature introduced in EJB 2.0). This means that the program is very robust against the modification of the database. Program code for transaction control is also not required. This class is deployed in a J2EE-compliant application server with home and remote interfaces (the details of the interfaces are not covered in this book.)

An EJB client program calls the methods defined in the EJB bean class, such as getNodeValueInfo() and setContent() in Listing 11.12. The former method returns information stored in the database (the class NodeValueInfo is included on the CD-ROM). The latter method updates a value of the persistent data. If this method is called, an SQL query is submitted to a database. However, the EJB bean does not know the database (table) name and the actual SQL query. The EJB container manages the process.

The information to associate an entity bean and a database is stored in an XML document called a deployment descriptor. It can be created by a Wizard-like GUI or other tools.

EJBs are deployed as distributed objects based on Java RMI-IIOP. That means an EJB object in an EJB container can call other EJBs in other containers located somewhere in the network. It is a big weapon for load balancing large-scale Web applications. On the other hand, if our system is local and relatively small, using EJB may be expositive. For example, although a CMP bean automates database access, it is sometimes not effective because it may retrieve unused values.

The simple example shown in Listing 11.12 is an entity bean that relates a record in a single database table. However, as we have shown with examples in previous sections, multiple tables are required to represent an XML document. They are often in a one-to-many relationship. Some techniques to handle the relationships with CMP and BMP are in the EJB 2.0 tutorial available at

We briefly introduced EJB and a sample program. One big question is when to use EJB. Suppose we have an existing system or we are designing a new Web application. Should we use the EJB framework for the application?

A simple answer depends on the scalability and extensibility of the system. If it is large or it will be extended in the near future, there is no doubt about using EJB. EJB reduces the cost of developing transaction control, database connection, security, and so on. It is easy to run multiple servers for accepting a large number of requests by combining EJBs in a distributed environment. If an existing system is developed by using Java beans, it is easy to move to an EJB environment.

Another key factor is the reusability of business logic. We can distribute the logic as EJB beans that can work on any J2EE-compliant application server.

     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows