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.
Introduction
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:
@Entity
@Table(name="TRANSACTIONS")
@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;
@ManyToOne
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;
@Entity
@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:
@OneToMany(mappedBy="accounts",fetch=FetchType.EAGER,cascade=CascadeType.MERGE)
private List<Transaction> transactionsCollection; [1]
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="ACCOUNTS_CUSTOMERS",
joinColumns=@JoinColumn(name="ACCOUNTS_ID"),
inverseJoinColumns=@JoinColumn(name="CUSTOMERS_SSN"))
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
.unmodifiableCollection(getTransactionsCollection());
}
public void processTransaction(Transaction transaction)
throws Exception {
setBalance(getBalance() + transaction.getSignedAmount());
if (getTransactionsCollection() == null) {
this.transactionsCollection = new ArrayList<Transaction>();
}
getTransactionsCollection().add(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]
}
...
@Action(Action.ACTION_TYPE.UPDATE)
public String updateCustomer(Customer customer) throws Exception {
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
customer = em.merge(customer); [3]
em.getTransaction().commit();
} 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]
aCustomer.setTitle(title);
aCustomer.setFirstname(firstName);
aCustomer.setLastname(lastName);
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:
http://localhost:9080/BankEJB3Web/
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:
https://www14.software.ibm.com/iwm/web/cc/earlyprograms/rational/RAD75OpenBeta/
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
LATEST COMMENTS
MC Press Online