15 Introduction to Enterprise JavaBeans

Enterprise JavaBeans (EJBs) technology is one aspect of the JEE specification that also includes specifications for servlets, messaging, Java Server Pages, and Java Messaging and other components.

EJBs appear to be more difficult than they really should be. The apparent complexity of the infrastructure of EJBs carries with it a big tradeoff. The JEE architecture handles much of the scaling and integrity issues required for robust enterprise code. This includes database connection pooling and transaction services, so the bottom line is that the complexity is worth the tradeoff for these types of enterprise applications. Simpler applications may be well served by the use of simpler architectures, such as the use of only Web server servlets for your application.

DISTRIBUTED COMPUTING

Enterprise JavaBeans bring the benefits of Java-built components to distributed, transaction-oriented systems. An EJB can be instantiated (that is, created) on a remote system and then respond to message requests from an application on a local system. Furthermore, EJBs can contain and manage transaction definitions. EJBs automatically participate in a transactional model as defined by your application. (In a transactional model, either all the work in a transaction is guaranteed to be intact, or committed to a database, or none of it is.)

Unfortunately, EJBs and ordinary JavaBeans share the same name. This has undoubtedly been the source of endless confusion among inexperienced developers, recruiters, and nontechnical managers. The fact is that EJBs and ordinary JavaBeans have very little to do with each other. Their only real thread of commonality is that both EJBs and ordinary JavaBeans are attempts to move software development in a more componentized direction.

JavaBeans are Java components defined in a way that makes them easy to use. In most functional respects, the JavaBeans specification is similar to the ActiveX specification, except what is specific to Java. JavaBeans are simply regular Java classes that employ a certain convention for getting and setting their internal values or properties. When a JavaBean implements the JavaBean API, the class is able to interact with other Java classes in a simple, standard fashion. For example, the GUI design tools that are a part of many integrated development environments expect you to code JavaBeans.

In contrast, EJBs are business logic components. They are designed to provide back-end business logic, particularly for thin client applications. They operate through interfaces and are largely ignorant of what is happening between the human and client application. Best of all, EJBs don’t have to manage the complex system plumbing that is normally associated with remote component management and transaction integrity control. All these system-level issues (e.g., component invocation, life-cycle management, security, and transaction semantics) are handled by the EJB infrastructure. A major design objective of the EJB spec is to allow developers to focus on writing code that solves the business problem(s) at hand rather than the technical issues surrounding the management of remote distributed component services.

The EJB specification is primarily an effort to standardize remote component-management techniques available to Java components. It also attempts to simplify and improve existing techniques, such as Common Object Request Broker Architecture (CORBA) and Distributed Component Object Model (DCOM). EJB is very Java-centric; it fits naturally into the Java language.

EJBs running in EJB containers (the supporting software that wraps around the EJBs) represent the best possible environment for developing the middle tier for robust, scalable applications. EJBs are written in Java. They are independent of the platform and the operating system. They are able to scale horizontally (inside a single system or across multiple systems) and vertically (using multiple systems for individual deployment tiers).

THE DIFFERENT KINDS OF EJBS

EJBs come in three flavors: SessionBeans, EntityBeans, and MessageBeans. Session-Beans are intended for storing session-related data or may be used as a simple remote API. EntityBeans are representations of persistent objects usually in databases. MessageBeans are activated in response to messages and are intended to provide the logic for processing the message.

SessionBeans can be either stateless or stateful. A stateless SessionBean is simply a remote API. It has no knowledge of you before you invoke its methods and it keeps no memory of you after you invoke it. In the client, you create references to access it, you call its methods passing arguments, and you get back a result. This type of EJB might be used for a complex calculation or, perhaps, to perform a very simple database operation that does not need any transaction logic, such as accessing commonly reused data or values.

For a stateful SessionBean, the word session is truly appropriate. When you create a reference to a stateful SessionBean in a client, a parallel copy of the Session-Bean is created in the EJB container. One client, one bean. As you interact with the SessionBean, you can change its internal variables and the SessionBeans maintains this state from one call to another. Although stateful SessionBean could be used to represent database objects, they might more commonly be used to represent temporary working copies of data that might or might not be eventually committed to more persistent storage. For example, a stateful SessionBean might be created to represent a shopping cart. The application might store and remove items in the cart. At some point, the application might discard the cart or save it to the database, possibly using an EntityBean to do so.

An EntityBean is intended to be a representation of a persistent object that is usually stored in a database. If you like, you can code the logic to retrieve and store the object (bean-managed persistence), or you can let the EJB container do the work for you (container-managed persistence).

EntityBeans extend the EntityBean parent class. Unless you are using container-managed persistence, an EntityBean will require additional methods for creating new entities (which you can think of as rows in a database), saving and loading the entities, and looking them up by various keys and arguments. All the methods for creating and looking them up (various find methods) are defined in the home interface and have their parallel versions in the implementation class. If you are using container-managed persistence, much of this work is done for you.

A MessageBean is a message listener that consumes messages from a queue or a durable subscription. The messages may be sent by any JEE component—from an application client, another enterprise bean, or a Web component—or from an application or system that does not use JEE technology.

CONTAINER SERVICES

EJBs can define the following control options at the class or the method level. By default, the class settings are applied to each method, but an individual method can define its own setting.

Security: What rights are required by the client in order to create this class or perform its methods? EJBs can use the new security model built into Java 2 to define and control access rights.

Transaction: What transaction level is supported or required by this bean? Here are the possibilities:

  • TX_BEAN_MANAGED

  • TX_SUPPORTS

  • TX_NOT_SUPPORTED

  • TX_REQUIRED

  • TX_REQUIRES_NEW

  • TX_MANDATORY

These settings indicate the valid transaction contexts for the bean. (It may be necessary for the client to first establish a new transaction context in order to meet the transaction requirements of the bean.)

Isolation level: What JDBC isolation level does the client require when a read is performed? The possibilities are TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, and TRANSACTION_SERIALIZABLE.

The container manages the transaction context and client/server connection on behalf of the client. The client does not need to be directly involved in details of the transaction semantics, such as begin transaction, commit, or rollback. Instead, the container creates a simplified client view of the EJB for the client, and the client can access the EJB as if it were a simple remote object. If the client needs to, however, it can adjust the default transaction behavior of the EJB.

What’s more, the EJB specification requires that the EJB server container provides extensive supporting software. This includes database connection pooling and transaction services. This code shouldn’t have to be rewritten for every application. Once it is right, it will be right for everybody. You don’t have to reinvent the wheel.

THE INTERFACES AND THE IMPLEMENTATION CLASS

Actually developing an EJB (of whatever type) requires that the developer code two interfaces and the implementation class. You might expect some relationship to exist between the interfaces and the class. There is a relationship, but it is not the usual relationship between classes and interfaces. The implementation class does not implement (in the Java sense) either of the two interfaces you have to code. You will grow accustomed eventually to the somewhat nonstandard relationship between the interfaces and the class. Initially the relationship is confusing. Keep in mind that the interfaces are for the client—the application that will be using the EJB—and things will be clearer.

The first interface you need to code is the remote interface. Believe it or not, this is what your implementation class will implement in reality, although it does not need to implement the interface in the Java sense of the word. The remote interface is intended for the client. It is a description of the business methods that are accessible to the client once the EJB is created.

public interface MyEJBInterface extends EJBObject
{
        public String getMyEJBValue() throws RemoteException;
 }

The second interface you code is the home interface. The home interface is what the client will use to create the reference to the EJB. In fact, the home interface returns the remote interface but triggers in the EJB container the entire supporting infrastructure required to create or instantiate the implementation class. The home interface may contain multiple creation methods based on key lookup or creation. It can also contain methods to create multiple instances of beans based on a selection criterion that reflects range.

public interface MyEJBHome extends EJBHome
{
         MyEJBInterface create() throws RemoteException, CreateException;
}

The implementation class itself is really the meat of the business logic you are providing—it is the real EJB. This class will either extend SessionBean, EntityBean, or MessageBean, depending on the type of EJB you are creating.

The implementation class will contain the methods that you defined in the remote interface class. This class must also contain the methods required to support the entire interaction with the EJB container.

public class MyEJB implements SessionBean
{
        public String getMyEJBValue() { return "some value"; }
        public void ejbCreate() {}
        public void ejbRemove() {}
        public void ejbActivate() {}
        public void ejbPassivate() {}
        public void setSessionContext(SessionContext sc) {}
}

For SessionBeans, these methods include the various life-cycle methods: create, remove, activate, passivate, and setContext. In stateless SessionBeans, you can implement trivial versions of these methods because essentially you are simply creating a remote API. That is what is shown in this example. Once you go beyond stateless SessionBeans, you will need to do more. For one thing, you will probably need multiple creation methods. For each create() method you defined in the home interface (such as create(), create(String key), and create(int numberKey)), you will need a corresponding ejbCreate (such as ejbCreate(), ejbCreate(String key), and ejbCreate(int numberKey)) in the implementation class. The passivate and activate methods are associated with saving and restoring the state of the bean if the container needs to swap it to disk.

Once you’ve coded the bean and its interfaces, you are ready to deploy. Deployment is specific to the application server that is in use. Basically, you will need to tell the server where the code is to implement the bean and define its characteristics: session stateless, session stateful, entity bean-managed, or entity container-managed. Depending on the type of bean, you will need to define additional things. Deployment will generate the code that the client needs to access the EJB. During this process, you will give a name to the EJB. This name will be the name used to actually locate the EJB.

ACCESSING THE BEAN FROM THE CLIENT

The Java Naming and Directory Interface (JNDI) provides the facilities for finding the remote server on which the EJB runs and for obtaining a reference to it. The InitialContext is the starting point for this lookup process. The lookup() method itself obtains the reference which is, in fact, a reference to the home interface. The home interface is used for actually creating the EJB and obtaining an interface to access its methods.

        Context initial = new InitialContext();
        java.lang.Object objref = initial.lookup("MyEJBName");
        MyEJBHome home = (MyEJBHome)
        PortableRemoteObject.narrow(objref,MyEJBHome .class);
        MyEJBInterface myEJB = home.create();
// Now you can use the EJB.
        String value = myEJB.getMyEJBValue();

EXERCISES

To do any exercises with EJBs, you will need a JEE-compliant application server. You can download the JEE SDK from the Java Sun Web site. It contains everything you will need to develop and test EJBs but is not a robust implementation that could be used in a production environment. The Java Sun Web site at http://java.sun.com/JEE/tutorial/index.html contains an excellent beginner’s tutorial.

Following are high-level steps to code, deploy, and use a simple stateless Session-Bean. The Java Sun tutorial provides details on how to do each of these steps.

  1. Download the JEE SDK from Java Sun and install the software.

  2. Code and compile the ConverterBean example found in the Getting Started Section of the tutorial.

  3. Code the ConverterClient application that accesses the ConverterBean.

  4. Start the JEE Server.

  5. Deploy the ConverterBean.

  6. Execute the ConvertClient application. If you have all the pieces in place, the application should access the ConverterBean class instance running in the application server, invoke the currency conversion methods in the sample, and display the results of the conversion.

REVIEWING THE EXERCISES

Although this simple example is relatively trivial, in the real world, EJBs are used for complex business logic and especially for database interactions. The objective of this simple example was to expose you to the complex infrastructure required to develop in the JEE environment. Try to understand how the various interfaces and pieces of code interact in order to implement EJBs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset