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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020