Enterprise JavaBeans (EJB) is a fancy name, so let me break it down for you. The Enterprise part tells you that EJB is for business applications, and JavaBeans are simply software components. Moreover, because Java is the language of the Internet, EJB must be software components for e-business. JavaBeans (without the Enterprise) have been around for a couple of years but were only GUI components; you still had to develop business back-ends for JavaBean-based GUI applications. To support online transaction processing, you need business components more than fancy GUI components, and you need e- commerce applications developed with business components that scale well and that are easy to use and portable to other platforms.
Three other business component strategies have also been available for some time: Common Object Request Broker Architecture (CORBA), Distributed Common Object Model (DCOM), and Remote Method Invocation (RMI). However, CORBA is too complex, DCOM is too Microsoft-centric, and RMI has poor scalability and no inherent transaction processing. Optionally, without component architectures, you can develop your business back-ends by using Common Gateway Interface (CGI) and RPG, but CGI is too kludgy, and CGI applications developed with RPG are too platform-centric.
Such problems with those older business component architectures are the reasons many companies now build e-commerce applications using EJB. EJB was designed to provide a standard architecture for object-oriented (OO) business applications that are easy to develop and deploy. EJB was intended to let computer scientists do their systems programming and also to let business programmers develop their business applications. In this article, I show you the basics of EJB architecture and explain how that architecture makes developing robust e-commerce applications easy.
APIs, Beans, and Containers
EJB has four fundamental elements: the remote interface, home interface, enterprise bean itself, and container (see Figure 1). The first element, the remote interface, is a list of functions that a client may invoke to manipulate the state of a business entity. Think of the remote interface as the client applications view of a host-based business entity. The remote interface works seamlessly through a proxy service hosted by a Web application server
such as BEA Systems WebLogic, IBMs WebSphere, or Bluestone Softwares Sapphire/Web.
The second element of EJB is the home interface, which is a sort of entity factory. The client uses it to create new entities or retrieve an existing entity or set of entities. For most EJB servers, the state of an entity bean is maintained in a relational database, such as DB2/400. When a client application uses the home interfaces create method, a record representing that entity is inserted in DB2/400. When a client application uses one of the home interfaces entity-specific find methods, enterprise beans materialize from existing DB2/400 records based on various selection criteria. (For more information on remote and home interfaces, see Enterprise JavaBeans: Show Me the Code! MC, July
1999.)
The third element of EJB is the enterprise bean itself. The enterprise bean implements the host-based Java code for all the business methods of the remote interface and for the create and find methods of the home interface. The client application accesses these methods of the enterprise bean through the remote and home interfaces via proxy services of an EJB-enabled Web application server. The enterprise bean also has many important methods that are inaccessible to the client, such as its life-cycle methods: ejbLoad, ejbStore, ejbCreate, and ejbRemove. These four methods are invoked respectively by the container at the appropriate time to read, update, write, and delete records from DB2/400.
That brings me to the container, the fourth element of EJB. The container provides a host-based environment for the enterprise bean. The client application programmer doesnt need to know anything about the container; its use is transparent to the client. Like a Java applet, an enterprise bean doesnt define the complete application; it defines only custom parts of that application. However, whereas an applet is hosted by a browser, an enterprise bean is hosted by a Web application server with the help of the container. The container provides a safe environment for EJB and also supports standard services for it.
These standard services show how the EJB architecture really shines. The container manages system and application resources such as memory, connection pools, and thread pools. The costliest processes on the AS/400 are job starts and file opens. EJB containers manage resource pools of Java threads and SQL connections. Java threads are analogous to AS/400 jobs, and SQL connections are hooks into DB2/400. Containers provide other important features, such as caching, security, transaction management, and data persistence. I discuss transaction management and data persistence later, but realize that those features are what make EJB architecture perfect for Web applications.
Four Beans
There are four types of enterprise beans. The stateless and stateful enterprise beans are collectively known as session beans, and the bean-managed persistence and container- managed persistence enterprise beans are collectively known as entity beans. Stateless session beans are host-based components that do not maintain any user or entity states between client method invocations. In contrast, stateful session beans maintain client states and have one-to-one relationships with clients. Stateful session beans are essentially application jobs.
Whereas stateful session beans represent user jobs, entity beans represent business entities. For EJB applications hosted by an AS/400, an entity bean has a one-to-one relationship with a DB2/400 record. Think of DB2/400 as your preferred data persistence engine that manages your applications data. In reality, not only can entity beans use any relational database for persistent storage, but they can also use object-oriented databases (OODBs) and flat-file systems. The entity bean provides a Java OO class wrapper for your business data.
As I mentioned earlier, there are two types of entity beans: bean-managed persistence and container-managed persistence. With bean-managed persistence, the entity
bean programmer explicitly codes those four life-cycle methods of an enterprise bean (ejbLoad, ejbStore, ejbCreate, and ejbRemove). Legacy programmers have been writing that type of code every day for the last several years, so the process doesnt seem like a big deal, but it is. That code takes a lot of effort, but container-managed persistence relieves the programmer of all the read/write responsibility. To use container-managed persistence, simply specify the entity bean name, file name, and mapping of the Java class attributes to relational data in a special EJB file called a deployment descriptor (see Figure 2). You must still code into the entity bean business methods such as deposit and withdraw methods of an account entity bean, but you dont need to code the four life-cycle methods or the find methods.
Record Locking
There is a problem with EJB. Its not a new problem, just a new twist to an old one. Remember that an entity bean represents a business entity. Now, suppose you deploy an EJB application, and clients Bill, Bob, and Jane are all using entity bean InvoiceBean. All three happen to be working with invoice number 6753 and access the same enterprise bean in main memory. If Bills client application invokes a method that changes an attribute of InvoiceBean 6753, the other client applications access that change even if Bill is not finished modifying the invoice or if Jane modifies it before Bill posts his final change.
This problem is nothing new to AS/400 programmers. What is new is that, to solve this problem, you must now use the record locking facilities of SQL instead of those of RPG and COBOL. Had Bill used a typical RPG, the program would have locked the record because he got to the record first and read it for update. However, EJB implementations do not use dynamic record access; they use SQL access. SQL records do not lock on reads. To prevent update anomalies when developing SQL-based applications, you must use the transaction semantics of commitment control. Here again, EJB containers do most of the transaction management for you.
Dirty Phantoms
To resolve update anomalies that occur when Bill, Bob, and Jane access the same entity bean, you need only do a little work setting up the EJB. To do that, you need to know about SQL isolation levels and EJB transaction attributes, but before I go into that, let me categorize update anomalies into three types: dirty reads, nonrepeatable reads, and phantom reads. A dirty read occurs when a record read by one client is modified by another client but not yet committed. A nonrepeatable read occurs when one client reads a record a second time after another client has changed that record since it was first read. A phantom read occurs when a client rereads a group of records based on a selection criterion and another client has subsequently added a record that fits that selection predicate.
Setup work required to resolve EJB update anomalies involves specifying an isolation level (Figure 3) and transaction attribute (Figure 4) to be associated with your enterprise bean in its deployment descriptor (Figure 2). The isolation level table in Figure 3 shows that each option provides different levels of locking, from the loose locking of TRANSACTION _READ_UNCOMMITTED to the tight locking of TRANSACTION_SERIALIZABLE. You must remember that, as you tighten the isolation level, you impose a performance penalty on your application.
Commitment Control
Your selection of an isolation level defines the type of locking you want for your enterprise bean, but, to lock your record or records, you must use what is known as a commitment control boundary, or transaction. Transaction management can be messy to work with, but EJB architecture was designed to handle it for you. Without EJB transaction management, you would have to start a commitment control boundary, process the records, and, at the appropriate time, commit or roll back the changes. To allow EJB to manage transactions,
either specify one of the transaction attributes shown in Figure 4 for all the methods of an entity bean or specify different transaction attributes for each method of the entity bean.
You now have an entity bean that has a one-to-one relationship with a DB2/400 record. You also have an isolation level and transaction attribute associated with that entity bean. That entity bean may have a dozen different methods, all of which manipulate the state of the entity. Because youve delegated transaction management to EJB, you need not set up transaction boundaries. The entity bean container automatically starts a transaction boundary when the method of that bean is invoked. That transaction boundary is known as a transaction context. If you look over the transaction attributes in Figure 4, you see that, sometimes, existing transaction contexts are used for method invocations and, other times, new transaction contexts are created. At any rate, at some point, an enterprise bean method starts a new transaction context that may then be used in the invocation of other methods. That transaction context is even used in the invocation of methods of other enterprise beans. The point is that, upon return of the method that started the transaction context, the transaction is automatically committed, and if the method invocation incurs a Java exception, the transaction is automatically rolled back. When an application has a complex relationship between files (as all business applications do), a single transaction boundary ensures integrity of the database modifications to your n-tier, EJB-based e-commerce application.
The Buck Stops Here
I must admit that, even after much research into EJB, I still didnt get EJB transaction attributes. It seemed to me that there was a hole in the logic behind EJB transaction management. An enterprise bean method must start a transaction context, and when that method that started the context returns, the transaction is committed. Im repeating myself, but my point is that, when you apply the most basic standard OO encapsulation techniques to an entity bean, little mini-transactions fire off all over the place. For instance, you would have a bunch of setter methods for a customer entity bean. If I develop a client application that uses that customer bean and a user wants to modify several of a customers attributes, that client application will cause the EJB container to create and commit a new transaction for each invocation of a setter function. Thats doesnt solve update anomalies; its just a performance glut.
However, after pounding my head against my desk and reading a few hundred more pages of EJB documentation, I discovered how to plug the hole I thought Id found in EJB transaction management. I could associate transaction attributes to entity bean methods so the EJB container could start transaction boundaries and subsequently commit database changes, but I didnt realize, until I did further research, that stateful session beans could also have transaction attributes associated with their methods. I knew that an entity bean normally has a one-to-one relationship with a database record and that a stateful session bean has a one-to-one relationship with a client application. The obvious plug for that hole was to use the methods of stateful session beans as macros for the invocation of entity beans. You design session beans with coarse-grained methods that coordinate the fine-grained encapsulated methods of entity beans. Therefore, session beans prove the overall control of transactions across invocations of methods in the same EJB class or in different EJB classes.
Where Does EJB Fit In?
EJB clients can be Java applets running from a Web browser, Java applications running over TCP/IP, or servlets. Servlets are often used with EJB for two reasons. The first reason is that servlets simplify the user interface to HTML. The second reason is that many Internet firewalls do not support the low-level protocol of EJB. Servlets effectively convert that protocol to one all firewalls understand: HTTP. Believe it or not, EJB clients can also be non-Java clients that use Microsoft DCOM clients or OMGs CORBA because many
Web application servers can provide DCOM and CORBA proxy services for EJB components.
Will EJB architecture catch on? I think so. I think EJB will become a prevalent strategy for advanced e-commerce applications because the industry is ready for a standard cross-platform architecture for business components that scales well and is easy to use. Initially, you may find industrial-strength Web application servers that support EJB cost- prohibitive. I believe the reason for this high cost is that the top Web application servers support a variety of architectures in addition to EJB. Increasingly, however, new Web application servers enter the market that provide a limited number of services but specialize in EJB hosting. In addition, because these servers are implemented in 100% Pure Java, they run on the AS/400. The beauty of EJB architecture is that you can use a lightweight EJB server (on your AS/400 or your desktop) to launch a proof-of-concept application. Then, when management buys into this hot new technology, you can buy your industrial- strength application server, with which your EJB business components are completely plug-compatible.
Client
Remote Interface Home Interface
Enterprise Bean
Container
Container
Enterprise Bean
Figure 1: EJB architecture revolves around the remote interface, home interface, enterprise bean, and container.
(EntityDescriptor
beanHomeName ejb.OrderHome
enterpriseBeanClassName web.ejb.OrderBean
homeInterfaceClassName web.ejb.OrderHome
remoteInterfaceClassName web.ejb.Order
...
(controlDescriptors
(DEFAULT
isolationLevel TRANSACTION_SERIALIZABLE
transactionAttribute TX_REQUIRED
...
)
)
(environmentProperties
...
(finderDescriptors
findOrder(int aCustNo) (= custNo $aCustNo)
findOrder(int aOrderNo) (= orderNo $aOrderNo)
findOrdersDue(int aDueDate) (> dueDate $aDueDate))
)
(persistentStoreProperties
persistentStoreType jdbc
(jdbc
tableName denoncourt.orders
...
(attributeMap
; Entity Bean attr Database field
;orderNo ordrno
custNo custno
dueDate datdue
)
)
)
)
...
)
Figure 2: EJB 1.0 implementations use product-specific syntax such as this BEA WebLogic deployment descriptor.
TRANSACTION_READ_UNCOMMITTED Data changes immediately available, even without commit; loosest isolation level TRANSACTION_SERIALIZABLE Locks data until commit; tightest isolation level TRANSACTION_READ_COMMITTED Prevents dirty reads but allows nonrepeatable and phantom reads TRANSACTION_REPEATABLE_READ Prevents dirty and nonrepeatable reads but allows phantom reads
TRANSACTION_NONE Transactions not supported
Figure 3: Isolation levels for EJB transactions are the same as SQL.
TX_NOT_SUPPORTED Suspends existing transaction during method call TX_BEAN_MANAGED User-controlled transaction
TX_REQUIRED Uses transaction if it exists; otherwise, it creates one TX_SUPPORTS Uses existing transaction but, otherwise, doesnt create one TX_REQUIRES_NEW Creates new transactions and commits transactions before returning TX_MANDATORY Throws an exception if no transaction exists
Figure 4: For programmers, transaction management is simply associating an EJB transaction attribute with methods of an entity bean, and the EJB container does the rest.
LATEST COMMENTS
MC Press Online