Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Building the Architectural Prototype: Part 3

Part 3 of building the architectural prototype for our non-EJB solution covers the entity bean and DAO classes.

Entity Beans

The entity beans are where the business logic lies in our application. This logic implements the Business Rule Services layer from our architecture. It also represents the state of the attributes of the entity. At a minimum, entity classes will have attributes as well as accessors for those attributes. There are also value classes that are proxies for the entity beans. Previously we stated that these proxies insulate the application from future distributed architecture migrations and reduce network chatter. Today everything may be running on one machine, but tomorrow that may change.

Let's continue with our progression and introduce the CustomerBean class:

package com.jacksonreed;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Collection;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;

public class CustomerBean implements java.io.Serializable {

   private Integer customerId;
   private String customerNumber;
   private String firstName;
   private String middleInitial;
   private String prefix;
   private String suffix;
   private String lastName;
   private String phone1;
   private String phone2;
   private String EMail;
   private ArrayList roleBean;
   private ArrayList orderBean;

All attributes of the bean are declared private. Notice that the relationships to other classes, as specified in the class diagram, are represented as ArrayList objects. These lists would hold RoleBean and OrderBean objects, respectively.

public void CustomerBean() {
   RoleBean = new ArrayList();
   OrderBean = new ArrayList();
}
public Integer getCustomerId() {
   return customerId;
}
public void setCustomerId(Integer val) {
   customerId = val;
}
public String getCustomerNumber() {
   return customerNumber;
}
public void setCustomerNumber(String val) {
   customerNumber = val;
}
public String getFirstName(){
   return firstName;
}
public void setFirstName(String val){
   firstName = val;
}
public String getMiddleInitial(){
   return middleInitial;
}
public void setMiddleInitial(String val){
   middleInitial = val;
}
public String getPrefix(){
    return prefix;
}
public void setPrefix(String val){
    prefix = val;
}
public String getSuffix(){
    return suffix;
}
public void setSuffix(String val){
    suffix = val;
}
public String getLastName(){
    return lastName;
}
public void setLastName(String val){
    lastName = val;
}
public String getPhone1(){
    return phone1;
}
public void setPhone1(String val){
    phone1 = val;
}
public String getPhone2(){
    return phone2;
}
public void setPhone2(String val){
   phone2 = val;
}
public String getEMail(){
   return EMail;
}
public void setEMail(String val){
   EMail = val;
}

These are the accessors for the beans related to CustomerBean:

public ArrayList getRoleBean(){
   return roleBean;
}
public void setRoleBean(ArrayList val){
   roleBean = val;
}
public ArrayList getOrderBean(){
   return orderBean;
}
public void setOrderBean(ArrayList val){
   orderBean = val;
}

Some of the code below we saw as a preview in Chapter 9 when we re-viewed the data access architecture. Here the findByCustomerNumber() operation, which has been called by the use-case control class, is pre-sented in a more complete form:

public CustomerValue findByCustomerNumber
   (TransactionContext transactionContext, String
   customerNumber)
   throws RemulakFinderException, Exception {

   try {
    // Initiate and get the information from the DAO
    DataAccess custDAO = new CustomerDAO (transactionContext);
    CustomerValue custVal = (CustomerValue)
          custDAO.findByName(customerNumber);

    // Sets the values of the bean with the DAO results
    setCustomerValue(custVal);
    custDAO = null;
    return custVal;2
    }
    catch (DAOSysException se) {
      throw new Exception (se.getMessage());
    }
    catch (DAOFinderException fe) {
      throw new RemulakFinderException (fe.getMessage());
    }
}

The operation first must get a reference to the CustomerDAO class that carries out its findByName() request. Notice that the type of the custDAO attribute is DataAccess. CustomerDAO implements the Data Access interface presented in Chapter 9. This ensures, or enforces, that all DAOs implemented in Remulak adhere to the same behavioral contract. The return of the CustomerValue object must be cast because the return type of the interface is Object.

public void customerUpdate
    (TransactionContext transactionContext, CustomerValue
    custVal)
    throws RemulakFinderException, Exception {

    try {
      setCustomerValue(custVal);
      DataAccess custDAO = new CustomerDAO
      (transactionContext);
      custDAO.updateObject(custVal);

      custDAO = null;
    }
    catch (DAOSysException se) {
      throw new Exception (se.getMessage());
    }
    catch (DAODBUpdateException ue) {
      throw new Exception (ue.getMessage());
    }
}

In the case of customerUpdate() above and customerInsert() below, the CustomerValue object is passed in to the appropriate DAO operation.

public void customerInsert
    (TransactionContext transactionContext, CustomerValue
    custVal)
    throws RemulakFinderException, Exception {

    try {
     setCustomerValue(custVal);
     DataAccess custDAO = new
     CustomerDAO(transactionContext);
     custDAO.insertObject(custVal);

     custDAO = null;
    }
    catch (DAOSysException se) {
     throw new Exception (se.getMessage());
    }
    catch (DAODBUpdateException ue) {
     throw new Exception (ue.getMessage());
    }
}

The customerDelete() operation passes to the CustomerDAO delete Object() operation the customerId parameter:

public void customerDelete
    (TransactionContext transactionContext, Integer
    customerId)
    throws RemulakFinderException, Exception {

    try {
     DataAccess custDAO = new CustomerDAO
     (transactionContext);
     custDAO.deleteObject(customerId);

     custDAO = null;
    }
    catch (DAOSysException se) {
      throw new Exception (se.getMessage());
    }
    catch (DAODBUpdateException ue) {
      throw new Exception (ue.getMessage());
    }
}

public void setCustomerValue(CustomerValue val)
{
   log("Setting Customer Value");

   setCustomerId(val.getCustomerId());
   setCustomerNumber(val.getCustomerNumber());
   setFirstName(val.getFirstName());
   setMiddleInitial(val.getMiddleInitial());
   setPrefix(val.getPrefix());
   setSuffix(val.getSuffix());
   setLastName(val.getLastName());
   setPhone1(val.getPhone1());
   setPhone2(val.getPhone2());
   setEMail(val.getEMail());
  }

  public String toString() {
   return "[CustomerBean " + getCustomerId() + ", " +
       getFirstName() + ", " + getLastName() + "]";
  }

  private void log(String s) {
    System.out.println(s);
  }
}

Data Access Objects

Data access objects (DAOs) were introduced in Chapter 9 as the mechanism that Remulak uses to gain access to and update data about beans. We shall see that the DAOs also use the TransactionContext object to do much of their work. The TransactionContext object has been passed in from the use-case control class so that it can control the scope of the unit of work. Let's begin our analysis by looking at the CustomerDAO class and the findByName() operation.

package com.jacksonreed;
import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.sql.*;
public class CustomerDAO implements Serializable, DataAccess {
   private transient TransactionContext globalTran = null;
   private transient CustomerValue custVal = null;

   public CustomerDAO(TransactionContext transactionContext) {
      globalTran = transactionContext;
}

Notice that the constructor takes in a TransactionContext object as a parameter and assigns it to a local copy.

public Object findByName(String name)
   throws DAOSysException, DAOFinderException {

     if (itemExistsByName(name)) {
       return custVal;
       }
    throw new DAOFinderException ("Customer Not Found = "
          + name);
}

private boolean itemExistsByName(String customerNumber)
    throws DAOSysException {
   String queryStr ="SELECT customerId, customerNumber,
   firstName " +
   ",middleInitial, prefix, suffix, lastName, phone1,
   phone2 " +
   ",eMail " + "FROM T_Customer " +
   "WHERE customerNumber = " + "'" + customerNumber.
   trim() + "'";

   return doQuery(queryStr);
}

The findByName() operation, part of the DataAccess interface, works with a private operation, itemExistsByName(), to retrieve the CustomerBean state information. First the SQL query must be built. For variety, I show an unprepared statement here and later will present a sample prepared statement.

private boolean doQuery (String qryString) throws
DAOSysException {
     Statement stmt = null;
     ResultSet result = null;
     boolean returnValue = false;
     try {
       stmt = globalTran.getDBConnection().
       createStatement();
       result = stmt.executeQuery(qryString);
       if ( !result.next() ) {
         returnValue = false;
       }
       else {
           custVal = new CustomerValue();

           int i = 1;
           custVal.setCustomerId(new Integer(result.getInt
           (i++)));
           custVal.setCustomerNumber(result.getString(i++));
           custVal.setFirstName(result.getString(i++));
           custVal.setMiddleInitial(result.getString(i++));
           custVal.setPrefix(result.getString(i++));
           custVal.setSuffix(result.getString(i++));
           custVal.setLastName(result.getString(i++));
           custVal.setPhone1(result.getString(i++));
           custVal.setPhone2(result.getString(i++));
           custVal.setEMail(result.getString(i++));

           returnValue = true;
       }
    } catch(SQLException se) {
       throw new DAOSysException("Unable to Query for item " +
                            "\n" + se);

    } finally {
      globalTran.closeResultSet(result);
      globalTran.closeStatement(stmt);
    }
    return returnValue;
}

The doQuery() operation takes in the query previously built and executes it. Notice that it gets a Statement object by referencing the connection stored in the local copy of the TransactionContext object. The query is executed via the executeQuery() operation and if there is something found, a new CustomerValue object is created and its values set. At the end, both the ResultSet and the Statement objects are closed. These close operations are part of the services offered by the TransactionContext object.

public Object findByPrimaryKey(Integer id)
   throws DAOSysException, DAOFinderException {

   if (itemExistsById(id)) {
      return custVal;
   }
   throw new DAOFinderException ("Customer Not Found = " +
   id);
}

private boolean itemExistsById(Integer customerId)
   throws DAOSysException {
  String queryStr ="SELECT customerId, customerNumber,
  firstName " +
     ",middleInitial, prefix, suffix, lastName, phone1,
     phone2 " + ",eMail " + "FROM T_Customer " +
             "WHERE customerId = " + customerId;

  return doQuery(queryStr);
}

The findByPrimaryKey() operation, also part of the DataAccess interface, works very much like findByName(). They both use the same private doQuery() operation. The only difference between the two is that one uses the secondary access mechanism of name (customer number in our case) and the other uses the primary key (customer ID in our case).

public void deleteObject(Integer id) throws
        DAOSysException, DAODBUpdateException {

   String queryStr = "DELETE FROM " + "T_Customer" +
          " WHERE customerId = "
             + id;

   Statement stmt = null;
   try {
      stmt = globalTran.getDBConnection().
      createStatement();
      int resultCount = stmt.executeUpdate(queryStr);
      if ( resultCount != 1 )
        throw new DAODBUpdateException
         ("ERROR deleting Customer from" +
          " Customer_TABLE!! resultCount = " +
          resultCount);
   } catch(SQLException se) {
      throw new DAOSysException("Unable to delete for
      item " +
      id + "\n" + se);
   } finally {
      globalTran.closeStatement(stmt);
   }
}

The deleteObject() operation simply deletes a row from the T_Customer table on the basis of the primary key of customerId being passed in.

public void updateObject(Object model) throws
            DAOSysException, DAODBUpdateException {
   CustomerValue custVal = (CustomerValue) model;

   PreparedStatement stmt = null;
   try {
      String queryStr = "UPDATE " + "T_Customer" +
       " SET " + "customerNumber = ?, " +
       "firstName = ?, " +
       "middleInitial = ?, " +
       "prefix = ?, " +
       "suffix = ?, " +
       "lastName = ?, " +
       "phone1 = ?, " +
       "phone2 = ?, " +
       "eMail = ? " +
       "WHERE customerId = ?";

     stmt = globalTran.getDBConnection().
            prepareStatement(queryStr);
     int i = 1;
     stmt.setString(i++, custVal.getCustomerNumber());
     stmt.setString(i++, custVal.getFirstName());
     stmt.setString(i++, custVal.getMiddleInitial());
     stmt.setString(i++, custVal.getPrefix());
     stmt.setString(i++, custVal.getSuffix());
     stmt.setString(i++, custVal.getLastName());
     stmt.setString(i++, custVal.getPhone1());
     stmt.setString(i++, custVal.getPhone2());
     stmt.setString(i++, custVal.getEMail());
     stmt.setInt(i++, custVal.getCustomerId().intValue());

     int resultCount = stmt.executeUpdate();
     if ( resultCount != 1 ) {

     throw new DAODBUpdateException
          ("ERROR updating Customer in" +
           " Customer_TABLE!! resultCount = " +
           resultCount);
   }
  } catch(SQLException se) {
     throw new DAOSysException
         ("Unable to update item " +
          custVal.getCustomerId() + " \n" + se);
  } finally {
     globalTran.closeStatement(stmt);
  }
}

In the case of the updateObject() operation, I chose to use a prepared statement. Prepared statements generally perform better and are easier to build.

public void insertObject(Object model) throws
            DAOSysException, DAODBUpdateException {
   CustomerValue custVal = (CustomerValue) model;
   PreparedStatement stmt = null;
   try {
      String queryStr = "INSERT INTO " +
        "T_Customer" + " (" +
        "customerId, " +
        "customerNumber, " +
        "firstName, " +
        "middleInitial, " +
        "prefix, " +
        "suffix, " +
        "lastName, " +
        "phone1, " +
        "phone2, " +
        "eMail) " +
        "VALUES " +
        "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

      stmt = globalTran.getDBConnection().
               prepareStatement(queryStr);

      int i = 1;
      stmt.setInt(i++, custVal.getCustomerId().intValue());
      stmt.setString(i++, custVal.getCustomerNumber());
      stmt.setString(i++, custVal.getFirstName());
      stmt.setString(i++, custVal.getMiddleInitial());
      stmt.setString(i++, custVal.getPrefix());
      stmt.setString(i++, custVal.getSuffix());
      stmt.setString(i++, custVal.getLastName());
      stmt.setString(i++, custVal.getPhone1());
      stmt.setString(i++, custVal.getPhone2());
      stmt.setString(i++, custVal.getEMail());

      int resultCount = stmt.executeUpdate();
      if ( resultCount != 1 )
        throw new DAODBUpdateException
              ("ERROR inserting Customer in" +
              " Customer_TABLE!! resultCount = " +
              resultCount);
   } catch(SQLException se) {
     throw new DAOSysException
         ("Unable to insert item " + custVal.
          getCustomerId() +
                " \n" + se);
    } finally {
       globalTran.closeStatement(stmt);
    }
}

The insertObject() operation is virtually identical to update Object(), with the difference of the actual SQL statement. The remaining operations are private and used locally by the DAO to clean up resources used in the SQL calls.

private void closeResultSet(ResultSet result)
   throws DAOSysException {
   try {
      if (result != null) {
        result.close();
      }
   } catch (SQLException se) {
      throw new DAOSysException
          ("SQL Exception while closing " +
               "Result Set : \n" + se);
   }
}
private void closeStatement(Statement stmt)
       throws DAOSysException {
       try {
          if (stmt != null) {
            stmt.close();
         }
      } catch (SQLException se) {
         throw new DAOSysException
              ("SQL Exception while closing " +
                  "Statement : \n" + se);
       }
   }
   private void log(String s) {
      System.out.println(s);
   }
}

Front to Back in One Package

We have built quite a bit of logic for our non-EJB solution. When you download all the code, you will find similar constructs for all aspects of the application, including the order entry part. However, if you understand how this flow worked and how the software architecture is laid out, you will find that the other components are identical.

  • + Share This
  • 🔖 Save To Your Account