Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Mastering Enterprise JavaBeans™ and the Java 2 Platform, Enterprise Edition - Roman E

..pdf
Скачиваний:
42
Добавлен:
24.05.2014
Размер:
6.28 Mб
Скачать

C H A P T E R13

J2EE in the Real World:

Implementing Our E-Commerce

Entity Beans

n the previous chapter, we discussed the high-level requirements and object Imodel for an e-commerce deployment for Jasmine’s Computer Parts. In this chapter, we’ll tackle the entity beans that make up our object model. These entity beans represent the core of Jasmine’s business—Customers, Products, Orders, and Line Items. These are unlikely to change or evolve much over time because they are fundamental components of a retail business. By way of comparison, the session beans that we’ll design in the next chapter are likely to change more

often in the long run because they contain evolving logic.

The great news here is that we’ve already implemented two of the entity beans we’ll need in our e-commerce system:

■■We’ll reuse the Bank Account entity bean (from Chapter 8) for recording monetary data. Our session beans in the next chapter will use the Bank Account to bill the client once he or she has submitted an Order.

■■The Product entity bean (from Chapter 9) will come in handy for describing Jasmine’s product line. We’ll reuse this bean here.

We’ll also design three new entity beans: a Customer entity bean, an Order Line Item entity bean, and an Order entity bean. The motivation for designing these beans is in Chapter 12.

This chapter (as well as the next two) will be very code-intensive because we are getting into the guts of our e-commerce deployment. Feel free to flip back to the previous chapter at any time to remind yourself of the high-level relationships in our object model. When you’re ready, read on about our new entity beans—starting with the Customer bean.

361

Go back to the first page for a quick link to buy this book online!

362 M A S T E R I N G E N T E R P R I S E J A V A B E A N S

The Customer Entity Bean

Our Customer entity bean is useful for describing a user who wants to purchase goods from our online store. This Customer bean could easily be generalized to be a generic “Person” bean as well, representing anyone, not just a Customer.

Why do we need to encapsulate customer information?

1.We’ll need to track information such as the customer name, so that our Pricer session bean can calculate customer-specific discounts.

2.Our login screen will use Customer beans to authenticate users by checking the user’s permanent password.

3.We could also use the Customer’s address information to ship an order once it’s been placed.

Specifically, our Customer will model the following data:

■■Customer ID

■■The customer’s name (also functions as the customer’s login name to our Web site)

■■The customer’s address

■■The customer’s password (used to verify the customer’s identity)

For brevity, we’re going to assume that Customers are created via direct database inserts. A simple maintenance utility could easily be written to add new Customers via a GUI as well.

Customer.java

Let’s first look at our remote interface, Customer.java. This is the interface that clients of the Customer bean will be dealing with. Our EJB container will generate an EJB object that implements this interface. The code is shown in Source 13.1.

Our interface is fairly straightforward—we simply expose methods to get and set the fields of our Customer’s data.

CustomerBean.java

Our bean implementation is contained in CustomerBean.java, shown in Source 13.2.

To keep the code simple, we’re using container-managed persistence for our Customer bean. Hence, many of the EJB required methods have been left empty because the container will perform the persistent operations for us. We also don’t implement any finder methods—that is delegated to the container as well. Thus,

Go back to the first page for a quick link to buy this book online!

J2EE in the Real World: Implementing Our E- Commerce Entity Beans 363

package com.wiley.compBooks.ecommerce;

import javax.ejb.*; import java.util.Vector;

import java.rmi.RemoteException;

/**

*These are the business logic methods exposed publicly by Customerbean.

*This interface is what clients operate on when they interact with

*beans. The EJB Server vendor will implement this interface; the

*implemented object is called the EJB object, which delegates

*invocations to the actual bean.

*/

public interface Customer extends EJBObject {

// Getter/setter methods for entity bean fields

public String getName() throws RemoteException;

public void setName(String name) throws RemoteException;

public String getPassword() throws RemoteException;

public void setPassword(String password) throws RemoteException;

public String getAddress() throws RemoteException;

public void setAddress(String address) throws RemoteException;

}

Source 13.1 Customer.java.

package com.wiley.compBooks.ecommerce;

import java.sql.*; import javax.naming.*; import javax.ejb.*; import java.util.*;

import java.rmi.RemoteException;

/**

*This container-managed persistent entity bean represents

*a customer record.

*/

public class CustomerBean implements EntityBean {

Source 13.2 CustomerBean.java (continues).

Go back to the first page for a quick link to buy this book online!

364 M A S T E R I N G E N T E R P R I S E J A V A B E A N S

protected EntityContext ctx;

//------------------------------------------------------

// Begin Container-Managed fields //------------------------------------------------------

/*

*The customer's identification number. It's also our

*Primary Key.

*/

public String customerID;

/*

* The customer name */

public String name;

/*

* The customer address */

public String address;

/*

* The user's password for this customer record */

public String password;

//------------------------------------------------------

// End Container-Managed fields //------------------------------------------------------

public CustomerBean() { System.out.println(

"New Customer Entity Bean Java Object created by EJB Container.");

}

//------------------------------------------------------

// Begin business methods //------------------------------------------------------

public String getName() throws RemoteException { System.out.println("getName() called."); return name;

}

public void setName(String name) throws RemoteException { System.out.println("setName() called.");

this.name = name;

}

Source 13.2 CustomerBean.java (continues).

Go back to the first page for a quick link to buy this book online!

J2EE in the Real World: Implementing Our E- Commerce Entity Beans 365

public String getPassword() throws RemoteException { System.out.println("getPassword() called."); return password;

}

public void setPassword(String password) throws RemoteException { System.out.println("setPassword() called.");

this.password = password;

}

public String getAddress() throws RemoteException { System.out.println("getAddress() called."); return address;

}

public void setAddress(String address) throws RemoteException { System.out.println("setAddress() called.");

this.address = address;

}

//------------------------------------------------------

// End public business methods //------------------------------------------------------

//------------------------------------------------------

//Begin EJB-Required methods. The methods below are called

//by the Container, and never called by client code.

//------------------------------------------------------

/**

*Associates this Bean instance with a particular context.

*Once done, we can query the Context for environment info,

*such as Bean customizations via properties.

*/

public void setEntityContext(EntityContext ctx) throws RemoteException { System.out.println("setEntityContext called");

this.ctx = ctx;

}

/**

*Disassociates this Bean instance with a particular

*context environment.

*/

public void unsetEntityContext() throws RemoteException { System.out.println("unsetEntityContext called"); this.ctx = null;

}

Source 13.2 CustomerBean.java (continues).

Go back to the first page for a quick link to buy this book online!

366 M A S T E R I N G E N T E R P R I S E J A V A B E A N S

/**

*Called directly after activating this bean instance.

*You should acquire needed resources in this method.

*/

public void ejbActivate() throws RemoteException {

System.out.println("ejbActivate() called.");

}

/**

*Called directly before passivating this bean instance.

*Release any resources you acquired in ejbActivate() in

*this method.

*/

public void ejbPassivate() throws RemoteException {

System.out.println("ejbPassivate () called.");

}

/**

*Updates the database to reflect the current values of

*this object.

*

*Since we're using Container-Managed Persistence, the

*Container will automatically save our public container-

*managed fields into the database. We should perform

*any necessary pre-processing here.

*/

public void ejbStore() throws RemoteException { System.out.println("ejbStore() called.");

}

/**

* Updates this object to reflect any changes to the

*database data.

*Since we're using Container-Managed Persistence, the

*EJB Container will automatically set our public fields

*to the correct values. We then do post-processing

*here.

*/

public void ejbLoad() throws RemoteException { System.out.println("ejbLoad() called.");

}

/**

*Called when new database data is created.

*When the client calls the Home Object's create()

Source 13.2 CustomerBean.java (continues).

Go back to the first page for a quick link to buy this book online!

J2EE in the Real World: Implementing Our E- Commerce Entity Beans 367

*method, the Home Object then calls this

*ejbCreate() method.

*

*We need to initialize our Bean's container-managed

*fields with the parameters passed from the client,

*so that the Container can inspect our Bean and create

*the corresponding database entries.

*/

public void ejbCreate(String customerID, String name, String address, String password) throws CreateException, RemoteException { System.out.println("ejbCreate(" + customerID + ", " + name + ", " + address + ") called");

this.customerID = customerID; this.name = name; this.address = address; this.password = password;

}

/**

*The Container calls this after ejbCreate(). At this

*point, the bean instance is associated with

*its own EJB Object. You can get a reference to that

*EJB Object by querying the context. You'd use that

*EJB Object reference when calling an external module,

*and you'd like to pass a reference to yourself.

*/

public void ejbPostCreate(String customerID, String name, String address, String password) throws RemoteException { System.out.println("ejbPostCreate() called");

}

/**

*Called before the container removes entity bean data

*from the database. Corresponds to when client calls

*home.remove().

*/

public void ejbRemove() throws RemoteException { System.out.println("ejbRemove() called.");

}

// No finder methods - they are implemented by Container

//------------------------------------------------------

// End EJB required methods //------------------------------------------------------

}

Source 13.2 CustomerBean.java (continued).

Go back to the first page for a quick link to buy this book online!

368 M A S T E R I N G E N T E R P R I S E J A V A B E A N S

our entity bean is left with an ejbCreate() initializer, some empty EJB required methods, and some get/set methods.

As you can imagine, writing these get and set methods for entity beans such as this could become very tedious. Filling in the EJB required methods could also be a burden. In the future, Integrated Development Environments (IDEs), such as Inprise’s JBuilder or Symantec’s Visual Cafe, may provide facilities for automatically writing a husk of an entity bean for you, saving you time and allowing you to concentrate on the real infrastructure you’re developing.

CustomerHome.java

Our home interface defines mechanisms for creating and instantiating our Customer EJB objects, and it is depicted in Source 13.3. The class for the home object that implements this interface will be created automatically by the EJB container.

The home interface’s create() is used by client code to create a new customer. When create() is called, the container delegates the call to the bean implementation’s ejbCreate() method, which initializes things. Once the container sets up the database data, the create() method returns a new EJB object to the client code.

We also have a number of customized finder methods for locating existing customers, based on certain attributes such as the customer name and the customer’s address. We also have a way to find all customers—in this case, an Enumeration is returned (which will change to a Collection in Java 2).

package com.wiley.compBooks.ecommerce;

import javax.ejb.*;

import java.rmi.RemoteException; import java.util.Enumeration;

/**

*This is the home interface for Customer. This interface is

*implemented by the EJB Server's glue-code tools - the

*implemented object is called the Home Object and serves as

*a factory for EJB Objects.

*

*One create() method is in this Home Interface, which

*corresponds to the ejbCreate() method in the Customer file. */

public interface CustomerHome extends EJBHome {

Source 13.3 CustomerHome.java (continues).

Go back to the first page for a quick link to buy this book online!

J2EE in the Real World: Implementing Our E- Commerce Entity Beans 369

/*

*This method creates the EJB Object.

*Notice that the Home Interface returns an EJB Object,

*whereas the Bean returns void. This is because the

*EJB Container is responsible for generating the EJB

*Object, whereas the Bean is responsible for

*initialization.

*

*@param customerID The globally unique Customer ID.

*This serves as our primary key.

*@param name The full name of the Customer. This

*parameter should match the bank account

*record name.

*@param address The Customer's address.

*@param password The Customer's password.

*

* @return The newly created EJB Object. */

Customer create(String customerID, String customerName, String address, String password) throws CreateException, RemoteException;

//Finder methods. These are implemented by the

//Container. The functionality of these methods can

//be customized by using the EJB Container tools.

public Customer findByPrimaryKey(CustomerPK key) throws FinderException, RemoteException;

public Enumeration findByName(String name) throws FinderException, RemoteException;

public Enumeration findByAddress(String address) throws FinderException, RemoteException;

public Enumeration findAllCustomers() throws FinderException, RemoteException;

}

Source 13.3 CustomerHome.java (continued).

CustomerPK.java

The primary key class for our customers is a simple String for the Customer ID. This is the same Customer ID we defined in CustomerBean.java. This ID must be globally unique for all Customer bean instances. It is the responsibility of the creator of the Customer to assign the Customer a unique primary key when

Go back to the first page for a quick link to buy this book online!

370 M A S T E R I N G E N T E R P R I S E J A V A B E A N S

package com.wiley.compBooks.ecommerce;

import java.io.Serializable;

/**

*Primary Key class for our Customer container-managed

*persistent entity bean

*/

public class CustomerPK implements java.io.Serializable {

/*

*Note that the primary key fields must be a

*subset of the the container-managed Bean

*fields. The fields we are marking as

*container-managed in our Bean are customerID,

*name, and address. Therefore our PK fields

*need to be from that set.

*/

public String customerID;

public CustomerPK(String customerID) { this.customerID = customerID;

}

public CustomerPK() {

}

public String toString() { return customerID.toString();

}

public int hashCode() {

return customerID.hashCode();

}

public boolean equals(Object cust) {

return ((CustomerPK)cust).customerID.equals(customerID);

}

}

Source 13.4 CustomerPK.java.

the Customer is created via its home interface. The code for our primary key is shown in Source 13.4.

The Deployment Descriptor

Finally, we have our Customer’s deployment descriptor. We use the deployment descriptor to declaratively specify attributes about our bean, such as persistence,

Go back to the first page for a quick link to buy this book online!