Thu, Jun
3 New Articles

Taming EJB 3 Development with Rational Application Developer 7.5 and WebSphere 7

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

Harness RAD 7.5 power to persist data in DB2 for i.


I believe that EJB 3 and its core element, Java Persistence API (JPA), have finally fixed what had been broken in the J2EE data persistency specification. The inherent complexity of previous EJB versions significantly reduced the adoption of this technology. With the introduction of EJB 3, the sanity returned into the world of enterprise Java development. EJB3 is a new programming paradigm that rests on Plain Old Java Objects (POJOs), Java annotations, and the dependency injection design pattern. With EJB3, you can create well-performing, high-quality applications faster and at a lower cost.


In this article, I use a sample banking application to illustrate how to use JPA tooling available in the Rational Application Developer (RAD) 7.5 to dramatically speed up the data layer development process. I also share with you programming tips and techniques that help you efficiently employ JPA concepts such as entity detachment and merging, object-relational mapping, and entity inheritance.


As a starting point, I use a sample banking application described in the Rational Application Developer V7 Programming Guide Redbook. The original version of the application uses the Container Managed Persistence (CMP) EJBs 2.1 as well as the container managed relationships (CMRs). It employs the Model-View-Controller (MVC) design pattern to separate the presentation layer from the business logic layer. The user interface is implemented with JSP and HTML scripts. To illustrate the EJB 3 concepts, I completely re-wrote the data model layer, leaving the presentation layer basically unchanged. To facilitate the development process, I used Rational Application Developer 7.5 and then deployed the modified application to WebSphere Application Server 7. As of writing, both products were in beta versions (see "Additional Material" at the end of this article).

Sample Application Walkthrough

Physical Database Model

Let's start the analysis with a quick look at the bank's application database. Figure 1 shows the data model diagram.



Figure 1: Sample bank application data model  (Click images to enlarge.)


In Figure 1, schema ITSOBank contains just four tables: CUSTOMER, ACCOUNT, TRANSACTIONS, and ACCOUNTS_CUSTOMERS. There is a many-to-many relationship between customers and accounts. In other words, one customer can have multiple accounts, and conversely, one account can belong to multiple customers (for example, a joint account of a married couple). To correctly represent the multiplicity of this relationship, a join table ACCOUNTS_CUSTOMERS has been defined in the data model. The ACCOUNTS_CUSTOMERS table has two foreign key constraints:


  • AC_CUST_FK represents the one-to-many relationship between CUSTOMER and ACCOUNT.
  • AC_ACCOUNT_FK represents the one-to-many relationship between ACCOUNT and CUSTOMER.


Note that jointly the two FK constraints correctly represent the many-to-many relationship between ACCOUNT and CUSTOMER tables.


The transaction history for an account is stored in the TRANSACTIONS table. The one-to-many relationship between accounts and transactions is encapsulated in the TRANS_ACCOUNT_FK foreign key constraint defined in the TRANSACTIONS table.


Creating the Application Projects

The first step in the development process is to create in RAD 7.5 a new Enterprise Application Project. Let's call the project BankEJB3EAR. The New EAR Application Project wizard sets the Target Runtime to WAS V7.0 and EAR version to 5.0. These are the required values, so leave them unchanged. Next, create the EJB Project called BankEJB3. We will not use the EJB Client JAR module, so you can switch this option off on the second page of the New EJB project dialog. The EJB project is by default added to the EAR project that has been created in the previous step.


Creating the Database Connection

In the RAD, switch the perspective to JPA. This is a new perspective in RAD 7.5 that allows you to work with every aspect of enterprise Java persistency. In fact, I could create a separate JPA project to group all data access artifacts in one place. While this makes sense for larger projects, I like to keep things simple, so we'll store the connection information and the entities classes in the EJB project. In the JPA perspective, find the Data Source Explore panel. Right-click the Databases folder and select New. The New Connection dialog appears. Fill the connection attributes as shown in Figure 2. Use the values specific to your environment.



Figure 2: Database connection parameters


To avoid password prompting, select the Save password check box. Check the connectivity by pressing the Test Connection button. Click Next. A production System i box can contain hundreds or thousands of schemas. So, to speed up the look-up process, you can scope the connection to just one schema. In this case, I set the filter so that only objects in schema ITSOBANK are visible. This is illustrated in Figure 3.



Figure 3: Setting a schema filter for the connection


Click Finish to create the new connection.

Still in the JPA perspective, right-click the newly created connection (myi5) and select Add JDBC connection to Project. In the Project selection dialog that appears, choose the BankEJB3 project.


Reverse Engineering the Entity Model


Switch to the J2EE perspective. Right-click the BankEJB3 project and select JPA Tools > Add JPA Manager Beans. On the JPA Manager Bean wizard that appears, select Create New JPA Entities. On the Generate Entities dialog, select myi5 from the Connection pull-down menu and ITSOBANK from the Schema pull-down. Click Next. On the Generate Entities from Tables dialog, change the package name to itso.bank.model.ejb. This is required to match the names expected by the Web module that implements the presentation layer. Note also that the entity name for the TRANSACTIONS (plural) has been changed to Transaction (singular). JPA Manager Bean wizard shows again. This time, however, there is a list of three entities that were generated by RAD. Select all three entities and press Next as shown in Figure 4.



Figure 4: JPA Manager Bean Wizard


Note there is no entity bean for ACCOUNTS_CUSTOMERS table. Can you guess why? Yes, this a join table that is used to represent the many-to-many relationship.


The next dialog is Tasks. It allows you to validate the attributes of the entities that were generated by the wizard. For example, the Relationships task for the Account bean shows that the wizard properly deduced the relationships between Account and Customer as well as between Account and Transaction. See Figure 5.



Figure 5: Relationships between entities


Select the Other task for any of the beans. This dialog allows you to change the default name of the manager bean. It also has a link that allows you to configure the project for JDBC deployment. Click this link as shown in Figure 6.



Figure 6: The Other task with the JDBC Deployment link


The Set up connections for deployment dialog appears. Change the JNDI connection name to jdbc/Bank_DB2fori as illustrated in Figure 7.



Figure 7: JDBC connection set up for deployment


Click OK and then Finish to finalize the process. Believe it or not, this creates the bulk of the code that is needed to implement the database access layer of the application.


Inheritance in the Object Model

The sample application needs to differentiate between two fundamental types of transactions: credit and debit. The natural approach would be to create two classes--Credit and Debit--that inherit from Transaction. So, for example, an instance of Credit would have its own copy of the locally defined state and the state inherited from a Transaction. Of course, we want the Credit to be persisted in the database. The same applies to a Debit instance. The only difference between Debit and Credit is that in case of a debit the amount property is subtracted from the account's balance while for credit the amount is added to the balance.


The single-table strategy seems to be perfect to store this class hierarchy. In the single-table strategy, the table must contain enough columns to store all various states for all classes in the hierarchy. In our case, the TRANSACTIONS table contains the AMOUNT column that can store current state for both Debit and Credit subclasses. How do we know, though, whether a row in TRANSACTIONS represents a Credit or a Debit? Well, the TRANSACTIONS table contains a column named TRANSTYPE. This is a special-purpose column called a "discriminator column." I use the appropriate annotations to inform the persistency manager how to handle the inheritance and how to discriminate between the subclasses. Consider the following Transaction class code excerpt:




@Inheritance                                                         [1]          

@DiscriminatorColumn(name="TRANSTYPE")                               [2]

public abstract class Transaction implements Serializable {   [3]

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)         [4]

       private int id;

       private String transtype;

       @Temporal(TemporalType.TIMESTAMP)                      [5]

       private Timestamp transtime;

       private int amount;


       private Account accounts;

... }


In the above example, both the @Entity and @Table annotations were generated by the wizard. At [1], I inserted the @Inheritance annotation to indicate that Transaction is the root class in a hierarchy. The inheritance strategy defaults to SINGLE_TABLE, so I don't have to specify the strategy parameter on the annotation. At [2], I define the @Discriminator annotation with the name parameter to specify the name of the column that will store the discriminator values. The discriminator values are defined in subclasses (see below). At [3], I define the Transaction as an abstract class, because the root in the hierarchy will not have to be persisted. Only the concrete subclasses need to be stored in the database. At[4], the @Id annotation is augmented with @GeneratedValue to indicate that the ID column in TRANSACTIONS is an identity column that will automatically generate key values on insertion of a new row. At [5], I add the @Temporal annotation to generate timestamp values at the object instantiation.


Finally, I add the following method to the Transaction class:


public int getSignedAmount() throws Exception


       throw new Exception("Transaction.getSignedAmount invoked!");



This method will be overridden by the subclasses.


Creating New Entity Beans

To create a new entity bean such as Credit, right-click the BankEJB3 project and select New > Class. The New Java Class dialog appears. Define the class as shown in Figure 8.



Figure 8: Creating the Credit subclass


Note the settings for package and Superclass properties. Once the class is created, open it in the editor and add the @Entity annotation just above the class declaration. To add the necessary import, right-click in the editor pane and select Source > Organize imports. There is probably an error at the @Entity annotation stating that the Credit entity is not specified in the persistence unit. To fix this problem, open the persistence.xml descriptor, which is in the JPA Content folder under BankEJB3 project. Click the Persistence Unit (BankEJB3) node in the Overview section and then click the Add button next to it. In the Add Item dialog that appears, select Class (the only option). A new entry under Persistence Unit (BankEJB3) node is added. Edit the class name in the Details section as shown in Figure 9.



Figure 9: Adding Credit entity bean to the Persistence Unit


Save the persistence descriptor (Ctrl-S). Next, right-click the Credit.java source under ejbModule and select JPA Tools > Add JPA Manager Beans to add the manager bean and configure the entity (see the "Reverse Engineering the Entity Model" section for details).


After adding the @DiscriminatorValue annotation at [1] and implementing the getSignedAmount method at [2], the final version of the Credit class is shown below:


package itso.bank.model.ejb;

import javax.persistence.DiscriminatorValue;

import javax.persistence.Entity;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;


@DiscriminatorValue("Credit")                                              [1]


public class Credit extends Transaction {

       public int getSignedAmount() throws Exception {               [2]

              return getAmount();





The Debit class is created in the analogous manner. The getSignedAmount method, however, returns the negative amount:


public int getSignedAmount() throws Exception


  return -getAmount();



Customizing the Entity Fetch and Merge Behavior

The Account entity bean generated by the wizard also requires couple of quick modifications. First, I want to make sure that when an Account bean is instantiated, all related transactions are also fetched from the database and materialized. This can be achieved by specifying the FetchType.EAGER parameter on the @OneToMany annotation. In addition, when an Account bean is saved by the persistence manager (merge operation), all related transactions, including the transactions that have been added or deleted, must also be persisted. Note that by default no operations are cascaded to related entities when persistence manager operations are applied to an Account instance. This default behavior can be overridden by adding the CascadeType.MERGE parameter to the @OneToMany annotation. These concepts are illustrated in the following code snippet:



private List<Transaction> transactionsCollection;                          [1]





private List<Customer> customerCollection;                                 [2]


Note that in the code sample above, I changed the type declaration at [1] and at [2] from Set to List. This is needed to match the interfaces used in the presentation layer.


The Account bean also implements two additional methods that are shown below:


public java.util.Collection<Transaction> getLog() {

              return java.util.Collections



public void processTransaction(Transaction transaction)

              throws Exception {

       setBalance(getBalance() + transaction.getSignedAmount());

       if (getTransactionsCollection() == null) {

              this.transactionsCollection = new ArrayList<Transaction>();





The only remaining change necessary in the entity model is adding the FetchType.EAGER parameter in the Customer bean as illustrated below:


@ManyToMany(mappedBy="customerCollection", fetch=FetchType.EAGER)

private Set<Account> accountCollection;


Implementing the Session Façade

The presentation layer communicates with the entity model through a session façade. This helps isolate the persistency layer from the user front-end application. In this case, the façade is implemented as a stateless session bean called BankFacade. You'll find the entire implementation in the downloadable image (see "Additional Material" section). Here, I will call out several methods to illustrate the more interesting programming techniques. So, to manage the entities, the session bean takes advantage of the entity manager beans that RAD generated. Each entity has its matching manager bean. For example, to manage the Customer entity, the wizard generated the CustomerManager bean. The manager bean handles all aspects of an entity life cycle. Thus it implements methods to create, delete, and update the entity as well as various find and get methods, such as findCustomerBySsn, getCustomerByTitle, etc. Let's examine a code excerpt from the getEntityManager method in the CustomerManager class:


private EntityManager getEntityManager() {

       EntityManagerFactory emf = Persistence

              .createEntityManagerFactory("BankEJB3");               [1]

       return emf.createEntityManager();                             [2]




public String updateCustomer(Customer customer) throws Exception {

       EntityManager em = getEntityManager();                                    

try {


       customer = em.merge(customer);                                       [3]


} catch (Exception ex) {





The getEntityManager method returns a reference to the entity manager. The persistency unit name (BankEJB3) is passed as a parameter to the createEntityManagerFactory method at [1]. Then at [2], the EntityManagerFactory is used to obtain the reference to the EntityManager instance. The updateCustomer method uses the EntityManager to save the current state of a Customer bean. This is accomplished at [3] by invoking the merge method on the EntityManager.


As mentioned, the session bean uses the entity manager beans to handle the entity persistence. Consider the following code fragment that shows the updateCustomer method that is exposed by BankFacade to clients that wish to persist changes in a Customer bean:


private CustomerManager cm = new CustomerManager();                  [1]   


public void updateCustomer(String ssn, String title, String firstName,

              String lastName) throws Exception {

       Customer aCustomer = cm.findCustomerBySsn(ssn);        [2]




       try {

              String result = cm.updateCustomer(aCustomer);          [3]

       } catch (Exception ex) {

              throw new Exception(aCustomer.getSsn());




Here, at [1], the manager bean is instantiated. At [2], the SSN is used to find a Customer instance and attach it into a persistence context. Then at [3], the updateCustomer method that I discussed earlier in this section is invoked to update the bean's state.


Adding the Presentation Layer

As mentioned, the presentation layer is implemented with JSP, servlets, and HTML pages. A detailed discussion of this layer goes beyond the scope of this article. One thing that is worth pointing out is the EJBBank class that constitutes the glue that binds the application layers. It obtains the reference to the BankFacadeRemote interface using the dependency lookup. This traditional form of dependency management is required since the EJB 3 dependency injection works only with servlets and session beans. Here's the pertaining code fragment from EJBBank class:


private BankFacadeRemote getBankEJB() throws Exception {

 if (bankEJB == null) {

       try {

              Context ctx = new InitialContext();

              bankEJB = (BankFacadeRemote)                    ctx.lookup(BankFacadeRemote.class.getName());                     [1]

       } catch (NamingException e) {

              throw new Exception("Unable to create EJB: "

                           + BankFacadeRemote.class.getName(), e);



 return bankEJB;



At [1], the JNDI lookup is used to create a reference to the remote interface of the session bean. The reference is then used to call various methods on the session beans. The remote methods return the entities as POJOs. This is the beauty of the EJB 3 model; no Data Transfer Object (DTO) classes are necessary to transfer data between layers. This dramatically simplifies the architecture and also improves performance. For example, consider the implantation of the getCustomer method in the EJBBank class:


public Customer getCustomer(String customerNumber)

              throws Exception {

       try {

              return getBankEJB().getCustomer(customerNumber);

       } catch (Exception e) {

              throw new Exception("Unable to retrieve accounts for: "

                           + customerNumber, e);




In the above code, the method returns an object of type Customer. The customer class has been actually defined in the BankEJB3 project as an entity bean.


To complete the application, you can import the BankEJB3Web project contained in the downloadable image. After the import, remember to update the BankEJBEAR application descriptor to add the Web module.


Running the Application

To run the application, right-click the BankEJBEAR project in the J2EE perspective and select Run As > Run on Server. When the Run on Server dialog appears, select WebSphere Application Server v7.0 at local and click Finish. Watch for the WAS messages in the Console pane. Make sure that there are no errors. Point the browser to the following URL:




Note that you may need to change the port, depending on your system's configuration. If everything works fine, the following welcome page should appear:



Figure 10: Welcome page of the Bank application


Click the EJB3Bank link to start working with the app. Use SSNs such as 111-11-1111 or 222-22-2222 to retrieve existing customer data.


Additional Material

Download the source code that accompanies this article.


The open beta version of RAD 7.5 is available at the following URL:




The following publication can be helpful to those who want to learn more about the topics covered in this article:


Tuning DB2 concurrency for WebSphere applications, IBM white paper


Jarek Miszczyk

Jarek Miszczyk is a Lead Technical Consultant for System x Virtualization and Cloud Computing at the IBM STG Global ISV Enablement organization. He is located in Rochester, Minnesota. He can be reached by email at This email address is being protected from spambots. You need JavaScript enabled to view it..



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: