26
Fri, Apr
1 New Articles

Enterprise JavaBeans: Show Me the Code!

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

I can listen to only so much hype about a new technology before I finally have to shout, “Let me see some code!” I’ve been hearing about Enterprise JavaBeans (EJB) for some time now, and I have been responsible for spreading some of that EJB hype around myself. For instance, in the March 1999 issue of Midrange Computing, which focused on Java (and of which I was the editor), IBM’s Keith Rutledge said, “EJB is a standard computing model that works across computing platforms from different vendors.... EJB
makes it easier to write application logic and applications by handling the low-level infrastructure tasks—such things as threading, state management, resource pooling, and the like.”

Enough already; it’s time to look under the hood of an EJB application. The beauty of EJB is that the client Java application programmers don’t have to deal with the complexity of the host Java classes. The code presented in this article focuses on the client developer’s view. I overview server-side EJB development without presenting its code; the client programmer doesn’t need to “know” about it anyway.

Session Beans and Entity Beans

There are two basic types of EJB: session beans and entity beans. Examples of session beans might be a shopping cart or a grocery list of an e-commerce site. But ignore session beans for now; you won’t be using them until you begin the development of advanced e- commerce applications. This article’s focus is on entity beans. Entity beans are essentially Java wrappers for persistent data, and for us Java application programmers, our persistent data store is DB2/400. Typically, we will have an entity bean for each record format for the database files that comprise our e-commerce applications.

Wrapping Your Order: Paper or Plastic?

Remember that this is object-oriented (OO) programming. An entity bean not only provides methods that access the information of a Relational Database (RDB) file but also provides business methods that modify that information as well as methods that collaborate with other EJB. This article’s example bean is an OO wrapper for the information that is

contained in an RDB file called Order. The Order file has the simple format of order number (which is also the primary key), customer number, and due date.

There are four basic components to any EJB: two interfaces (one home interface and one remote interface) and two classes (the entity bean itself and a primary key class). An interface is simply a list of methods that some Java class must later implement—similar to a set of RPG IV D-specs that contains function and procedure prototypes. A bean’s home interface provides the CRUD: the EJB life-cycle methods for Creation, Retrieval, Update, and Deletion of an entity bean. Figure 1 shows the OrderHome interface with the declaration of the create and findByPrimaryKey methods—in other words, the Create and Retrieval of CRUD. So where’s the U and D? The Delete is provided for with the declaration of the remove method in the OrderHome’s base interface, EJBHome (see Figure 2). An Update method is not a required interface for the client, because the entity bean on the server makes the state of a modified entity persistent by updating the database at the appropriate times (using a function called ejbStore).

The Order interface, the second of the two interfaces, is in Figure 3; it simply provides two methods: getDueDate and getCustNo. For a more complete example, I’d also have numerous other methods (methods, for instance, that modify the entity’s attributes or provide collaboration with other associated entity beans). In the Order example, I would probably have getCustomer, addLineItem, and getLineItems methods.

The two classes are the primary key class and the entity bean. The primary key class is simply a class whose data members represent the full key of the entity. For the order entity, the order number is the full key, so the OrderPK class in Figure 4 is composed of but one attribute: an Integer order number. The entity bean class, OrderBean, is where the code for the Order and OrderHome interfaces is implemented. Figure 5 lists the methods of the OrderBean class minus their code implementations (which are beyond the scope of this article).

It is important to note that the client programmer will not be using the entity bean—not directly, that is. The client programmer uses the entity bean through what is known as the remote interface. The remote interface is composed of the business methods of the entity bean. The remote interface to the host-based OrderBean is shown in Figure 3. The entity bean is the Java class that provides the code implementation for the home and remote interfaces.

Bean-managed vs. Container-managed

The entity bean itself or its container can manage the persistent storage of an entity bean’s attributes. Persistence management by the entity bean is easier for us legacy programmers to understand because we are used to being responsible for implementing the code to create, read, update, and delete the DB2/400 records. In the documentation for EJB, it is almost expected that you’ll use Java Database Connectivity (JDBC) for database management, but it’s up to you. You could use IBM’s Java Toolbox for the AS/400’s record-level access classes, or you could use an OO database management system.

But an EJB strategy that may not be as easy to understand is container managed persistence. Sun’s preliminary EJB 2.0 specification includes strategies for the automation of RDB access for entity beans. That means you don’t have to write any CRUD code; all you have to do is specify, in a control file known as the deployment descriptor, the persistent storage type of JDBC and the file name followed by a table that maps the database field names with the entity bean’s attributes. Figure 6 shows an example deployment descriptor that you could use with BEA’s Weblogic for the specification of container-managed persistence for my Order entity bean.

Client Code

Regardless of which strategy I use to manage persistence, the client code required to access the Order entity bean (shown in Figure 6) remains the same. The Java class, appropriately

called Client, begins by qualifying itself as part of Midrange Computing’s EJB client package before it imports all of Midrange Computing’s EJB interface classes:

package com.midrangecomputing.ejb.client;
import com.midrangecomputing.ejb.interfaces.*;

The Client class then imports the Java packages required for the remote access of EJB. The first method of the Client class is called getInitialContext. The code for this method is typical of EJB clients; it specifies the properties of the EJB host, such as the URL of the host and its socket number as well as the user name and the user’s password.

This particular EJB client application uses a hardcoded order number to retrieve a remote reference to an entity bean. If the order is not found, the application creates one using a hardcoded customer number and due date. All this processing is done in the method called main. The main method begins by creating the object variables that contain the hardcoded values for the order number, customer number, and due date. The main method then creates an instance of the Order primary key class and sets its order number attribute to be the Integer object that contains the hardcoded order number:

OrderPK orderKey = new OrderPK();
orderKey.ordNo = ordNo;

At this point, the client application is ready to retrieve a remote reference to a server instance of the Order entity bean:

Context ctx = getInitialContext();

The client first invokes the getInitialContext method, which specifies to whom it is communicating. Then, it uses the lookup method of the Context class to enable a connection with the server’s implementation of the OrderHome interface. Remember that the home interface provides the life-cycle methods of an entity bean; it is with the variable called home that the client application will retrieve or create an order entity:

OrderHome home = (OrderHome) ctx.lookup(“ejb.OrderHome”);

The client then creates a variable whose type is the Order entity bean’s remote interface. Remember that the remote interface specifies the business methods for an entity bean:

Order remoteOrder = null;

The client then attempts to retrieve a remote reference to the Order entity bean with the findByPrimaryKey method of the OrderHome interface:

remoteOrder (Order) home.findByPrimaryKey(orderKey);

But if a reference to the remote order could not be had, the client application creates a new one using the create method of the OrderHome interface:

remoteOrder = home.create(ordNo, custNo, dueDate);

Either way, whether found by primary key or newly constructed, the remoteOrder variable contains a remote reference to the Order entity bean, which means the client application can invoke the methods of the remote interface:

System.out.println(“Order......: “ + ordNo +

“ Customer..: “ + remoteOrder.getCustNo() +

“ Due Date..: “ + remoteOrder.getDueDate());

The use of the remote invocation of the server-based entity bean for system output may seem overly trivial, but it nonetheless suggests the power of EJB. In a robust EJB application, the remote interface will contain business methods that the client is able to invoke to perform the complex tasks associated with that entity.

Needful Things

If the techniques shown in this order processing example were all that EJB provides, there’d be no reason to use this technology. And there’d be no reason to pay thousands, or tens of thousands, of dollars for an EJB server. The code that I’ve shown for the client side is simply a slight variation of Java’s Remote Method Invocation (RMI). So why not just use RMI, which is free? An Internet application that uses the object distribution strategies of RMI will work fine when 10 clients are accessing it. It will probably work fine when you have 20 clients attached, but when you have 100 or 1,000 clients...? RMI applications don’t scale well without complex systems programming. We are not systems programmers; we are business programmers. EJB applications scale well because the EJB servers handle performance, using such features as caching, resource pooling, and Least Recently Used (LRU) algorithms for memory management. Furthermore, EJB has sophisticated mechanisms for the management of transactions and commitment control—something all complex e-commerce applications will require.

The EJB Interface

The development of EJB applications can become quite complex, but the use of entity beans in client applications is simple. You use the home interface (OrderHome in my example) to control the life cycle of an entity bean. You use the remote interface (Order in my example) to invoke the business methods of an entity bean. You can manage the persistence of entity beans yourself, or you can delegate that responsibility to the container- managed persistence provided by the EJB server. By the end of this year, we will begin to see EJB Internet applications from Integrated Software Vendors (ISVs) that run great on the AS/400. Use of the Enterprise JavaBeans specification will become pervasive because it provides the technologies required for robust Internet e-commerce applications.

package com.midrangecomputing.ejb.interfaces;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
public interface OrderHome extends EJBHome {

public Order create(Integer ordNo, Integer custNo, Date dueDate)

throws CreateException, RemoteException;

public Order findByPrimaryKey(OrderPK primaryKey)

throws FinderException, RemoteException;
}

Figure 1: The OrderHome interface provides the life-cycle methods for an entity bean.

import java.rmi.*;
import javax.ejb.*;
public interface EJBHome implements Remote {

void remove(Handle);

void remove(Object);

EJBMetaData getEJBMetaData();
}

Figure 2: The OrderHome’s base interface, EJBHome, provides the methods required for the deletion of an entity.

package com.midrangecomputing.ejb.interfaces;
import java.rmi.RemoteException;
import javax.ejb.*;
public interface Order extends EJBObject { public java.util.Date getDueDate()

throws RemoteException;

public Integer getCustNo()

throws RemoteException;
}

Figure 3: The Order interface provides business methods for the manipulation of a business entity.

package com.midrangecomputing.ejb.interfaces;
public class OrderPK implements java.io.Serializable
{ public Integer ordNo; }

Figure 4: The attributes of the OrderPK class correspond to the full key of the RDB Order file.

package com.midrangecomputing.ejb.server;
import com.midrangecomputing.ejb.interfaces.*;
import javax.ejb.*;
import java.util.*;
import java.sql.*;

class OrderBean implements EntityBean {

Integer ordNo;

Integer custNo;

Date dueDate;

OrderBean();

boolean isModified();

String id();

void setModified(boolean);

void ejbActivate();

void setEntityContext(javax.ejb.EntityContext);

void unsetEntityContext();

void ejbPassivate();

void ejbLoad();

OrderPK ejbFindByPrimaryKey(OrderPK orderPK);

void ejbStore();

void ejbRemove();

OrderPK ejbCreate(Integer ordNo, Integer custNo, Date dueDate);

void ejbPostCreate(Integer ordNo, Integer custNo, Date dueDate);

Integer getCustNo();

Date getDueDate();

Connection getConnection();

static static {};
}

Figure 5: The OrderBean class provides code implementations for all the methods of the OrderHome and Order interfaces (shown in Figures 1-3).

(jdbc

tableName Order

(attributeMap

; EJBean attribute Database column name

;ordNo ORDNO

custNo CUSTNO

dueDate DUEDATE

)

)

Figure 6: The Client application uses an EJB remote interface to access the methods of a host-based entity bean.

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: