26
Fri, Apr
1 New Articles

E-business by Design with EJB

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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 application’s 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, IBM’s WebSphere, or Bluestone Software’s 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 interface’s create method, a record representing that entity is inserted in DB2/400. When a client application uses one of the home interface’s 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 doesn’t need to know anything about the container; its use is transparent to the client. Like a Java applet, an enterprise bean doesn’t 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 application’s 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 doesn’t 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 don’t need to code the four life-cycle methods or the find methods.

Record Locking

There is a problem with EJB. It’s 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 Bill’s 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 you’ve 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 didn’t “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. I’m 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 customer’s attributes, that client application will cause the EJB container to create and commit a new transaction for each invocation of a setter function. That’s doesn’t solve update anomalies; it’s 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 I’d 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 didn’t 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 OMG’s 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, doesn’t 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.

Don Denoncourt

Don Denoncourt is a freelance consultant. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Don Denoncourt available now on the MC Press Bookstore.

Java Application Strategies for iSeries and AS/400 Java Application Strategies for iSeries and AS/400
Explore the realities of using Java to develop real-world OS/400 applications.
List Price $89.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: