Divide and Conquer
The BookEaz system's design is composed of a fairly large collection of classes, ranging from the relatively simple to the rather complex. When working under a new paradigm such as EJB, I prefer to get my feet wet by starting with the simplest implementation task. The simplest BookEaz component is the Book Entity Bean, and it's used most simply in Use Case 6 (UC6), Maintaining the Inventory Database, so that's a good place to start the implementation phase.
UC6's functionality is manifested by the interaction of Book, an Entity Bean, and BookAdmin, a classic J2SE Java client class. Implementing Book introduces many of the fundamental tenets of EJB component construction, and implementing BookAdmin introduces the essential mechanisms for accessing and using those components.
Two Flavors of Entity Beans: CMP Versus BMP
So, it's time to start writing some code now, right? Well, not quite. One important aspect of Entity Beans must be covered before Book can be implemented, an aspect that determines how much code must be written and who, or what, is responsible for writing that code. Although it is true that somebody or something has to implement the methods declared in Book's two interfaces, a human might not have to do it; EJB is capable of generating many of an Entity Bean's method implementations.
The extent to which EJB is capable of generating method implementations is determined by the flavor of the Entity Bean. Yes, Entity Beans come in two exciting flavors: Container Managed Persistence (CMP) and Bean Managed Persistence (BMP).
Container Managed Persistence Beans
The implementation code for one Entity Bean often looks almost identical to the code for another; there are only so many sensible ways to implement a query, update, insert, or delete, after all. The same is true for getter (used for reading an attribute's value) and setter (used for specifying an attribute's value) methods; they all look much the same. Entity Beans are composed largely of database operations (finding, creating, updating, and removing entities), getters (retrieving attribute values), and setters (setting attribute values), so the fine folks who created the EJB specification realized that Entity Beans' code could often be automatically generated.
An entity with no "special needs" in its database operations, getters, or setters can be implemented as a CMP Bean. As of EJB 2.0, the number of special needs has been reduced to the point that almost all Entity Beans can be implemented as CMPs. The only special needs remaining are as follows:
-
Non-JDBC-compliant databasesThe CMP code generator knows how to generate only database operations that use JDBC, so if an Entity Bean uses, say, an object-oriented database that doesn't support JDBC, it cannot be a CMP Bean.
-
Disparate database constructsIf the database constructs through which an Entity Bean performs query operations differ from the ones it uses to perform updates, inserts, or deletes, the Entity Bean cannot be a CMP Bean. For example, if Book were to query from a database view, but update through a database stored procedure, it could not be implemented as a CMP Bean.
-
Unusual getters or settersIf an Entity Bean's getters and setters do anything other than simple assignment or return statements, it cannot be implemented as a CMP Bean.
Rule of Thumb 11
Under EJB 2.0, almost all Entity Beans can and should be implemented as CMP Beans.
The Book Entity Bean doesn't involve any of these complications, so you can implement it as a CMP. As a CMP Bean, it doesn't contain much handwritten implementation code, so you can implement it more quickly than under J2SE. More important, however, is that this decrease in the number of SLOC is accompanied by a corresponding decrease in the number of errors introduced by tired (from writing too much code), bored (from writing the same code over and over), and overstressed (from looming deadlines) coders.
Declaring Book's Remote Interface
The time has come to start writing some code. Book, the Entity Bean designed in Chapter 2, "Designing a Solution Using EJB," is made up of four items: the Book remote interface, the BookHome home interface, the BookBean implementation class, and the deployment descriptor. The task of implementing Book naturally falls into four subtasks, one for each item composing the Entity Bean. It seems sensible to start by coding the two interfacesBook and BookHomebecause they determine the shape and size of BookBean and the deployment descriptor (see Listing 3.1). Make sure you have installed the J2EE Reference Application Server before you proceed with coding.
Listing 3.1 Book's Remote Interface
package com.bookeaz.books; import javax.ejb.EJBObject; import java.rmi.RemoteException; /** * A Book offered for sale by BookEaz. This is the remote * interface part of the home/remote/implementation triad. */ public interface Book extends EJBObject { //Book's getters for accessing its attributes public String getISBNNumber() throws RemoteException; public String getTitle() throws RemoteException; public String getAuthor() throws RemoteException; public String getSubject() throws RemoteException; public Float getPrice() throws RemoteException; //You might expect corresponding setters, but //Books are largely read-only entities. The only attribute //that is subject to change on a regular basis is price. public void setPrice(Float inPrice) throws RemoteException; //However, the administrative use cases call for //updating titles, authors, etc., so you need some //way of doing so.... public void update(String inTitle,String inAuthor, String inSubject,Float inPrice) throws RemoteException; }
Discussion
Book conforms to a number of rules mandated by the EJB 2.0 specification:
It extends javax.ejb.EJBObject. This base interface provides Book with several useful utility methods, which can be safely ignored during this tutorial. They are discussed in detail in Part II.
Its methods are public. Neither Java nor the EJB spec allows protected or private methods to be declared, so Book's methods are all declared public.
Its methods all declare their propensity to throw javax.rmi.RemoteException. Book (and all Entity Beans, except Local Entity Beans, which are discussed later) throws this exception if anything goes irrecoverably wrong during any method implementations.
Its methods mention (in their parameter lists or as their return types) only objects that are "remotely accessible." The EJB 2.0 spec has a rather long-winded definition for the term "remotely accessible," but for the purposes of this tutorial, it means "objects that are Enterprise JavaBeans or implement the java.io.Serializable interface." Book, for example, mentions only objects of type java.lang.String and java.lang.Float, both of which implement java.io.Serializable. Therefore, Book passes the "remotely accessible" litmus test.
In addition to complying with the EJB 2.0 spec, Book also obeys the spirit of the EJB ethos. Like most typical Entity Beans, it is in many ways just an object wrapper around a set of persistent attributes. As such, Book has methods only for getting and setting its attributes' values; you won't find any high-level business methods offered by this Entity Bean.
In another respect, however, Book is an atypical Entity Bean remote interface. Most remote interfaces provide both a getter and a setter method for each attribute. Book, on the other hand, contains a getter for each of its attributes, but only one setter, the setPrice() method. Book is a "read mostly" Entity Bean; after a Book is created, there is rarely a need to change its information (such as ISBN, author, subject, or title), so these methods are intentionally removed from the remote interface. Because Book prices are subject to change, however, the Book remote interface provides a means for setting the price attribute.
Rule of Thumb 12
An Entity Bean attribute can be made "read-only" by simply excluding its setter method from the Bean's remote interface.
In most BookEaz use cases, Books are read-only entities. The only exception is UC6, which stipulates that the BookEaz administrative interface must be capable of updating a Book's persistent attributes. To simultaneously satisfy this requirement and the desire to provide a largely read-only Book, Book includes a method named update() that is capable of updating a Book's title, author, subject, and price.
Declaring Book's Home Interface
Book's home interface, like its remote interface, is short on lines of code but long on declarative power; the home interface, BookHome, merely declares methods for creating new Book instances and for finding existing ones (see Listing 3.2).
Listing 3.2 Book's Home Interface
package com.bookeaz.books; import javax.ejb.EJBHome; import javax.ejb.FinderException; import java.rmi.RemoteException; import java.util.Collection; /** * BookHome is the home interface for the Book Entity. * Being a home interface, it provides methods * for creating new Book instances and for * finding existing ones. */ public interface BookHome extends EJBHome { /** Create a new Book with the given ISBN, title, author, subject, and price. **/ public Book create(String inISBN,String inTitle, String inAuthor, String inSubject, Float inPrice) throws CreateException, RemoteException; /** * Find the Book whose ISBN is inISBN. * ISBNs uniquely identify Books. */ public Book findByPrimaryKey(String inISBN) throws FinderException, RemoteException; /** * Find books with names matching inTitle. */ public Collection findByTitle(String inTitle) throws FinderException, RemoteException; /** * Find books written by inAuthor */ public Collection findByAuthor(String inAuthor) throws FinderException, RemoteException; /** * Find books dealing with inSubject. */ public Collection findBySubject(String inSubject) throws FinderException, RemoteException; }
Discussion
BookHome's contents are largely mandated by the EJB 2.0 specification, which insists that Entity Bean remote interfaces obey these rules:
Home interfaces extend javax.ejb.EJBHome.
Home interfaces can declare any number of methods for creating new Entity Bean instances. These methods, which must have names beginning with create, are the EJB equivalent of constructors. BookHome's single create...() method accepts values for all the attributes of the Book being created. Create...() methods return remote interfaces to the Entity Bean instances they create.
Home interfaces can declare any number of methods for finding existing Entity Bean instances. These methods, whose names must start with find, are essentially wrappers around database queries. One of these "finder" methods must be named findByPrimaryKey(), and it must accept a single parameter containing the primary key for the Entity Bean being sought. Books use ISBNs as primary keys, and ISBNs are stored as Java Strings, so BookHome's findByPrimaryKey() method accepts a String parameter.
Finder methods can return a single instance (as findByPrimaryKey() does), or they can return multiple instances. Finder methods that return a single instance return a remote interface, so findByPrimaryKey() returns a Book remote interface. Finder methods that return multiple instances return a java.util.Collection or a java.util.Set containing instances of the home interface's corresponding remote interface.
Home interfaces can declare a third type of method, known as a home method. Although they are not used in this tutorial, they are discussed in depth in Part II.
Implementing BookBean
BookBean's implementation consists of two kinds of code. The majority of its implementation code is simple; there is nothing complex about the body of a getter or setter, after all, and getters and setters compose the vast majority of Book's methods. The rest of BookBean's code is more unpredictable (and thus more interesting); the bodies of ejbCreate() and update(), for example, are not completely rote in their composition.
The EJB creators recognized the dichotomy inherent in Entity Bean implementation code and decided to take advantage of it to make developers' lives a little easier. When implemented under the auspices of CMP, many of the obvious implementation tasks are handed over to the EJB environment. Those methods whose implementations are foisted onto EJB are referred to as auto-generated methods. These methods fall into two campsthose completely generated by EJB and those partially (somewhere between 0% and 100%) generated by EJB.
EJB auto-generates implementations for all declared getters and setters for CMP Entity Beans; if the Entity Bean's implementation class (BookBean, in this example) declares an abstract getter or setter for an attribute, EJB generates that getter's or setter's implementation. EJB performs auto-generation only for declared getters and setters; it never auto-generates one of its own volition. Furthermore, EJB doesn't allow developers to implement getters and setters for CMP Entity Beans; if you attempt to circumvent EJB and implement one by yourself, EJB will reject your Entity Bean.
Although EJB completely denies developers the privilege of implementing getters and setters, it does permit them to collaborate in implementing the second type of auto-generated methods, which consist of housekeeping methods that EJB normally auto-generates. If circumstances dictate, however, developers can implement parts of these methods. For example, every Entity Bean must have an ejbActivate() method, and EJB auto-generates it on your behalf. If, however, your Entity Bean's implementation also contains an implementation of ejbActivate(), EJB arranges for your implementation to be called by its auto-generated one; ejbActivate()'s implementation is then a collaboration between EJB and you.
Table 3.1 details the major types of methods in Entity Bean implementations and who is responsible for implementing them.
Table 3.1 CMP Implementation Responsibilities
Method |
Example |
Implemented by (EJB, Developer, or Both) |
Comments |
Getters and setters |
getISBNNumber(),setPrice() |
EJB |
Developer declares them as public abstract methods. |
ejbCreate...() |
ejbCreate(String inISBN...) |
Developer |
One ejbCreate...() for every create...() specified in the home interface. |
ejbPostCreate() |
ejbPostCreate(String inISBN...) |
Developer |
One for every ejbCreate...(); usually empty. |
find...() |
ejbFindByTitle (String inTitle) |
EJB |
EJB uses EJB-QL from the deployment descriptor to generate these methods (more on that in Chapters 6, "All About Deployment," and 7, "Entity Beans"). |
Housekeeping methods |
ejbActivate(), ejbPassivate(),ejbLoad(), ejbStore(),ejbRemove() |
Both |
EJB always auto-generate these methods. If implemented by the developer, EJB ensures that both the auto-generated and the hand-generated methods are invoked. |
Context manipulators |
setEntityContext(),unsetEntityContext() |
Developer |
These methods can be empty, but are usually implemented just as they are in BookBean. |
Business methods |
update(String[] values) |
Developer |
The burden of implementing business methods falls (as it always does) squarely on the developers' shoulders. |
Armed with this information, BookBean can now be implemented. Thanks to EJB, there is little actual coding work to be done within BookBean's confines, as you can see in Listing 3.3.
Listing 3.3 BookBean, Book's Implementation Class
import javax.ejb.EntityBean; import javax.ejb.EntityContext; import java.rmi.RemoteException; import javax.ejb.RemoveException; import javax.ejb.EJBException; /** * The back-end implementation of Book. **/ public abstract class BookBean implements EntityBean { /** * The EntityContext provides * information about the client who is using this Bean, * and also allows this Bean instance to access services * provided by the container. **/ private EntityContext context; /**Methods that must be declared in order to conform * to the EJB 2.0 spec. BookBean doesn't actually use * these methods, however. **/ public BookBean() {} public void ejbActivate() { } public void ejbPassivate() { } public void ejbLoad() { } public void ejbRemove() { } public void ejbStore() { } /** * Update method, the one-and-only "business method" * offered by Book. Note that ISBN cannot be * modified because it uniquely identifies a book. */ public void update(String inTitle,String inAuthor, String inSubject,Float inPrice){ //the outside world lacks access to these setters //because they aren't in the remote interface. They //can be accessed by the implementation, however. setTitle(inTitle); setAuthor(inAuthor); setSubject(inSubject) ; setPrice(inPrice); } /** * Abstract methods for getters and setters. Note that only * one setter, setPrice, exists; the other attributes are * read-only **/ public abstract String getISBNNumber(); public abstract String getTitle(); public abstract String getAuthor(); public abstract String getSubject(); public abstract Float getPrice(); public abstract void setPrice(Float inValue); /**Methods used by the EJB container to set * and unset the EntityContext **/ public void setEntityContext(EntityContext ctx) { context = ctx; } public void unsetEntityContext() { context = null; } }
Discussion
BookBean is a fairly typical CMP Entity Bean implementation class. It contains abstract getter and setter methods corresponding to the getters and setters declared in the Book remote interface. The EJB specification insists that getters and setters for CMP Entity Beans be abstract; the EJB container will provide concrete implementations for them on your behalf. It also contains a number of methods stipulated by the EJB 2.0 specification. Most of these methods contain empty bodies, a trait common in CMP Entity Beans; these empty implementations are subsumed by auto-generated methods supplied by EJB.
BookBean's most notable traits are the following:
It is an abstract class. EJB uses BookBean as a template to generate its own concrete implementation class, which is silently substituted for BookBean at runtime.
Its getters and setters are all abstract, as mandated by the EJB 2.0 specification for CMP Entity Beans. EJB graciously implements these methods on the developer's behalf.
In contrast to the Book remote interface, BookBean contains the full complement of getter/setter pairs. The setters for ISBN, title, author, and subject are not exposed to the general public (via Book), but BookBean uses them internally to manipulate their respective attributes.
All of BookBean's getters and setters have public visibility, regardless of whether they are visible to the outside world. The EJB 2.0 specification insists that all getters and setters be public, even if they are not to be used outside the Entity Bean's implementation. The visibility of getters and setters is determined by their presence or absence in the remote interface, not by their visibility (public, private, "package," or protected) declaration in the implementation.
The housekeeping methods (ejbActivate(), ejbPassivate(), ejbLoad(), ejbRemove(), and ejbStore()) are all empty implementations; EJB auto-generates their "real" implementations.
Notably absent from BookBean are any implementations of BookHome's find...() methods. EJB auto-generates find...() methods for CMP Entity Beans, so there is no need to implement them in BookBean.
Compiling Book's Java Code
Book's source code is available for download at the companion Web site. After downloading it, place it into a directory rooted at c:\bookeaz (for Windows systems) or ~/bookeaz (for Unix/Linux systems); this directory is referred to as <BOOKEAZ_HOME>. After installing the downloaded files, you will have a directory structure that looks like this:
c:\bookeaz classes src bookeaz books Book.java BookBean.java BookHome.java admin
Prerequisites for Compiling
To compile and run BookEaz code, your environment must be properly set up. Specifically, you need three software suites installed:
A Java Development Kit (JDK), version 1.3.1 or later, available at http://www.javasoft.com
Sun's J2EE Reference Server, available at http://www.javasoft.com and set up according to Appendix B
CloudScape's database system, which is bundled with Sun's J2EE Reference Server
In addition, you must have these environment variables set up for the compilation to proceed:
-
CLASSPATH must contain a reference to j2ee.jar (which is part of Sun's J2EE Reference Server) and BookEaz's classes directory (<BOOKEAZ_HOME>/classes). To add them to your CLASSPATH on Windows systems, issue this command from a command-prompt window:
set CLASSPATH=%CLASSPATH%;c:\j2ee\lib\j2ee.jar;c:\bookeaz\classes
PATH must contain a reference to the JDK bin directory. To add this reference to PATH on Windows systems, issue this command from a command-prompt window:
set PATH=%PATH%;<JAVA_HOME>\bin
<JAVA_HOME> is the topmost directory where JDK was installed; for example, on my computer, <JAVA_HOME> is c:\jdk1.3.1.
During the post-tutorial parts of this book, you will use a modern build tool named Ant to compile and deploy EJBs. In the interest of getting something compiled and running quickly, however, compile Book.java, BookHome.java, and BookBean.java by hand for now. Follow these steps to compile Book's constituents on a Windows-based system:
Open a command-prompt window from the taskbar.
Change directory to <BOOKEAZ_HOME>\src\com\bookeaz\books (<BOOKEAZ_HOME> is the root of BookEaz's installation directory, typically c:\bookeaz).
Compile all three EJB components by issuing javac d c:\bookeaz\classes Book*.java. This command compiles Book's components and places the resulting .class files into <BOOKEAZ_HOME>\classes\com\bookeaz\books.
After performing these steps, the <BOOKEAZ_HOME>\classes directory contains compiled versions of Book's three Java source files. You are now ready to deploy Book to the Application Server.