A S ESSION B EAN E XAMPLE 71Every create method in the home interface corresponds to an ejbCreate method in the bean class.. RemoteException; public Vector getContents throws RemoteExcep
Trang 1A S ESSION B EAN E XAMPLE 71
Every create method in the home interface corresponds to an ejbCreate
method in the bean class The signatures of the ejbCreate methods in the
CartEJB class follow:
public void ejbCreate(String person) throws CreateException
public void ejbCreate(String person, String id) throws CreateException
Compare the ejbCreate signatures with those of the create methods in the
Cart create(String person, String id) throws RemoteException, CreateException;
}
The signatures of the ejbCreateand createmethods are similar, but differ inimportant ways The rules for defining the signatures of thecreatemethods of ahome interface follow:
• The number and types of arguments in acreatemethod must match those
of its correspondingejbCreate method
• The arguments and return type of thecreatemethod must be valid RMItypes
• Acreatemethod returns the remote interface type of the enterprise bean
(But anejbCreate method returns void.)
• The throws clause of the create method must include the
java.rmi.RemoteException and thejavax.ejb.CreateException
Remote Interface
The remote interface, which extends javax.ejb.EJBObject, defines the ness methods that a client may invoke Here is the source code for the Cart
busi-remote interface:
Trang 2RemoteException; public Vector getContents() throws RemoteException;
}
The method definitions in a remote interface must follow these rules:
• Each method in the remote interface must match a method implemented inthe enterprise bean class
• The signatures of the methods in the remote interface must be identical tothe signatures of the corresponding methods in the enterprise bean class
• The arguments and return values must be valid RMI types
• Thethrows clause must include thejava.rmi.RemoteException
Helper Classes
TheCartEJBbean has two helper classes:BookExceptionandIVerifier The
BookExceptionis thrown by theremoveBookmethod and theIdVerifierdates thecustomerId in one of theejbCreatemethods Helper classes shouldreside in the EJB JAR file that contains the enterprise bean class
vali-State Management Modes
When you specify the deployment descriptor of a session bean, you must choosebetween two state management modes: stateful or stateless
Stateful Session Beans
The CartEJB example, discussed in Session Bean Class (page 66), has threeinstance variables:customerName,customerId, andcontents These variablesrepresent the conversational state of the shopping cart application Because the
CartEJB contains a conversational state, it is called a stateful session bean.The state is retained for the duration of the client-bean session When the clientremoves the bean, the session ends and the state disappears This transient nature
Trang 3S TATE M ANAGEMENT M ODES 73
of the state is not a problem, however, because when the conversation betweenthe client and the bean ends there is no need to retain the state
Stateless Session Beans
A stateless session bean does not maintain a conversational state for a particularclient When a client invokes the method of a stateless bean, the beans’s instancevariables may contain a state, but only for the duration of the invocation Whenthe method is finished, the state is no longer retained Except during methodinvocation, all instances of a stateless bean are equivalent, allowing the EJB con-tainer to assign an instance to any client
Because stateless session beans can support multiple clients, they can offer betterscalability for applications that require large numbers of clients Typically, anapplication requires fewer stateless session beans than stateful session beans tosupport the same number of clients
At times, the EJB container may write a stateful session bean out to secondarystorage However, stateless session beans are never written out to secondary stor-age Therefore, stateless beans may offer better performance than stateful beans
The home interface of a stateless session bean must have a singlecreatemethodwith no arguments The session bean class must contain oneejbCreatemethod,also without arguments (The arguments are only needed by stateful sessionbeans, which use them to initialize their states.)
Choosing Between Stateful and Stateless Session Beans
You should consider using a stateful session bean if any of the following tions are true:
condi-• The bean’s state must be initialized when it is created
• The bean needs to hold information about the client across method tions
invoca-• The client is an interactive application
Trang 474 S ESSION B EANS
Since the primary goal of a session bean is to represent a client in the J2EEserver, most of your session beans will be stateful However, sometimes you maywant to use stateless session beans:
• The bean performs a task that is not tailored to the needs of a particular ent For example, you might use a stateless session bean to fetch from adatabase a commonly used set of data
cli-• The bean doesn’t need to hold information about the client across methodinvocations
The Life Cycle of a Session Bean
A session bean goes through various stages during its lifetime, or life cycle Thelife cycle is managed by the EJB container, not by your applications Althoughyour applications cannot explicitly manage a bean’s life cycle, you’ll find theinformation in the following sections useful when you need to manage resourcessuch as database connections See Resource Connections (page 269) for details
The Stateful Session Bean Life Cycle
Figure 6 illustrates the stages that a session bean passes through during its time The client initiates the life cycle by invoking thecreatemethod.The EJBcontainer instantiates the bean and then invokes the setSessionContext and
life-ejbCreatemethods in the session bean The bean is now ready to have its ness methods invoked
busi-While in the ready stage, the EJB container may decide to deactivate, or vate, the bean by moving it from memory to secondary storage (Typically, theEJB container uses a least-recently-used algorithm to select a bean for passiva-tion.) The EJB container invokes the bean’sejbPassivatemethod immediatelybefore passivating it If a client invokes a business method on the bean while it is
passi-in the passive stage, the EJB contapassi-iner activates the bean, movpassi-ing it back to theready stage, and then calls the bean’sejbActivate method
At the end of the life cycle, the client invokes the remove method and the EJBcontainer calls the bean’sejbRemove method The bean’s instance is ready forgarbage collection
Your code controls the invocation of only two life cycle methods—thecreate
andremovemethods in the client All other methods in Figure 6 are invoked bythe EJB container TheejbCreatemethod, for example, is inside the bean class,allowing you to perform certain operations right after the bean is instantiated
Trang 5T HE L IFE C YCLE OF A S ESSION B EAN 75
For instance, you may wish to connect to a database in the ejbCreatemethod
See Resource Connections (page 269) for more information
Figure 6 Life Cycle of a Stateful Session Bean
The Stateless Session Bean Life Cycle
Because a stateless session bean is never passivated, its life cycle has just twostages: non-existent and ready for the invocation of business methods Figure 7illustrates the stages of a stateless session bean
Trang 676 S ESSION B EANS
Figure 7 Life Cycle of a Stateless Session Bean
Other Enterprise Bean Features
The topics that follow apply to both session and entity beans
Accessing Environment Entries
Stored in an enterprise bean’s deployment descriptor, an environment entry is aname-value pair that allows you to customize the bean’s business logic withoutchanging its source code An enterprise bean that calculates discounts, for exam-ple, might have an environment entry named “Discount Percent.” Before deploy-ing the bean’s application, you could assign “Discount Percent” a value of 05 onthe Environment tabbed pane of thedeploytool When you run the application,the enterprise bean fetches the 05 value from its environment
In the following code example, the applyDiscount method uses environmententries to calculate a discount based on the purchase amount First, the method
1 setSessionContext
2 ejbCreate
ejbRemove
Does Not Exist
Ready
Trang 7O THER E NTERPRISE B EAN F EATURES 77
locates the environment naming context by invoking lookup with the
java:comp/env parameter Then it callslookup on the environment to get thevalues for the “Discount Level” and “Discount Percent” names For example, ifyou assign a value of 05 to the “Discount Percent” name in thedeploytool, thecode will assign 05 to the discountPercent variable The applyDiscount
method, which follows, is in the CheckerEJB class The source code for thisexample is inexamples/src/ejb/checker
public double applyDiscount(double amount) { try {
double discount;
Context initial = new InitialContext();
Context environment = (Context)initial.lookup(“java:comp/env”);
Double discountLevel = (Double)environment.lookup(“Discount Level”);
Double discountPercent = (Double)environment.lookup(“Discount Percent”);
if (amount >= discountLevel.doubleValue()) { discount = discountPercent.doubleValue();
} else { discount = 0.00;
} return amount * (1.00 - discount);
} catch (NamingException ex) { throw new EJBException(“NamingException: “ + ex.getMessage());
} }
Comparing Enterprise Beans
A client can determine if two stateful session beans are identical by invoking the
isIdentical method:
Trang 878 S ESSION B EANS
bookCart = home.create(“Bill Shakespeare”);
videoCart = home.create(“Lefty Lee”);
.
if (bookCart.isIdentical(bookCart)) { // true }
if (bookCart.isIdentical(videoCart)) { // false }
Because stateless session beans have the same object identity, theisIdentical
method always returnstrue when used to compare them
To determine if two entity beans are identical, the client can invoke the tical method, or it can fetch and compare the beans’s primary keys:
isIden-String key1 = (isIden-String)accta.getPrimaryKey();
String key2 = (String)acctb.getPrimaryKey();
if (key1.compareTo(key2) == 0) System.out.println(“equal”);
Passing an Enterprise Bean’s Object Reference
Suppose that your enterprise bean needs to pass a reference to itself to anotherbean You might want to pass the reference, for example, so that the second beancan call the first bean’s methods You can’t pass the thisreference because itpoints to the bean’s instance, which is running in the EJB container Only thecontainer may directly invoke methods on the bean’s instance Clients access theinstance indirectly by invoking methods on the object whose type is the bean’sremote interface It is the reference to this object (the bean’s remote reference)that the first bean would pass to the second bean
A session bean obtains its remote reference by calling thegetEJBObjectmethod
of theSessionContextinterface An entity bean would call thegetEJBObject
method of the EntityContext interface These interfaces provide beans withaccess to the instance contexts maintained by the EJB container Typically, thebean saves the context in thesetSessionContextmethod The following codefragment shows how a session bean might use these methods
public class WagonEJB implements SessionBean { SessionContext context;
public void setSessionContext(SessionContext sc) { this.context = sc;
}
Trang 9O THER E NTERPRISE B EAN F EATURES 79
public void passItOn(Basket basket) { .
basket.copyItems(context.getEJBObject());
} .
Trang 1080 S ESSION B EANS
Trang 11Characteristics of Entity Beans 82Persistence 82
Shared Access 83Primary Key 83
A Bean-Managed Persistence Example 83Entity Bean Class 84
The EntityBean Interface 84Home Interface 92
Remote Interface 94Tips for Running theAccountEJB Example 94Mapping Table Relationships For Bean-Managed Persistence 96One-to-One Relationships 97
One-to-Many Relationships 100Many-to-Many Relationships 108About Container-Managed Persistence 111
A Container-Managed Persistence Example 111Primary Key Class 111
Creating a Primary Key Class 112Class Requirements 113
Bean-Managed Persistence and the Primary Key Class 113Container-Managed Persistence and the Primary Key Class 114Getting the Primary Key 114
Handling Exceptions 115
Trang 1282 E NTITY B EANS
The Life Cycle of an Entity Bean 116
Characteristics of Entity Beans
Entity beans differ from session beans in several ways Entity beans are tent, allow shared access, and have primary keys
persis-Persistence
Because the state of an entity bean is saved in a storage mechanism, it is tent Persistence means that the entity bean exists beyond the lifetime of theapplication or the J2EE server process If you’ve worked with databases, you’refamiliar with persistent data The data in a database is persistent because it stillexists even after you shut down the database server or the applications it ser-vices
persis-There are two types of persistence: bean-managed and container-managed Youdeclare the persistence type with the deploytool, which stores the information inthe entity bean’s deployment descriptor
Bean-Managed Persistence
With bean-managed persistence, the entity bean code that you write contains thecalls that access the database The ejbCreate method, for example, will issuethe SQLinsertstatement You are responsible for coding theinsertstatementand any other necessary SQL calls See A Bean-Managed PersistenceExample (page 83)
Container-Managed Persistence
If the container manages an entity bean’s persistence, it automatically generatesthe necessary database access calls For example, when a client creates an entitybean, the container generates a SQLinsertstatement The code that you writefor the entity bean includes no SQL calls As a result, the entity bean is indepen-dent of any particular datastore, such as a relational database Because of thisindependence, the beans are portable across all compliant J2EE servers
Trang 13A B EAN -M ANAGED P ERSISTENCE E XAMPLE 83
Entity beans with container-managed persistence has several advantages overthose with bean-managed persistence:
• They require less code
• Because they don’t contain the database access calls, their code is dent of any particular data store, such as a relational database And because
indepen-of this independence, the beans are portable across all compliant J2EEservers
• Their relationships with other objects are managed by the EJB container,not by routines in bean’s code
Shared Access
Entity beans may be shared by multiple clients Because the clients might want
to change the same data, it’s important that entity beans work within tions Typically, the EJB container provides transaction management You spec-ify the transaction attributes in the bean’s deployment descriptor You do nothave to code the transaction boundaries in the bean—the container marks theboundaries for you See Transactions (page 235) for more information
transac-Primary Key
Each entity bean has a unique object identifier A customer entity bean, forexample, might be identified by a customer number The unique identifier, or pri-mary key, enables the client to locate a particular entity bean For more informa-tion, see the section, Primary Key Class (page 111)
A Bean-Managed Persistence Example
The entity bean illustrated in this section represents a simple bank account Thestate of the entity bean is stored in themyaccounttable of a relational database
Themyaccount table was created by the following SQL statement:
CREATE TABLE myaccount (id VARCHAR(3) CONSTRAINT pk_account PRIMARY KEY, firstname VARCHAR(24),
lastname VARCHAR(24), balance DECIMAL(10,2));
Trang 1484 E NTITY B EANS
To write an entity bean, you must provide the following code:
• Entity Bean Class (AccountEJB)
• Home Interface (AccountHome)
• Remote Interface (Account)This example also makes use of the following classes:
• A helper class namedInsufficientBalanceException
• A client class calledAccountClient.The source code for this example is in theexamples/src/ejb/accountdirec-tory To compile the code, go to the examples/src directory and type ant account
Entity Bean Class
The sample entity bean class is called AccountEJB As you look through itscode, note that it meets the requirements of every entity bean:
• It implements theEntityBean interface
• The class is defined aspublic
• The class cannot be defined asabstract orfinal
• It implements zero or moreejbCreate andejbPostCreate methods
• It implements the finder methods (only for bean-managed persistence)
• It implements the business methods
• It contains an empty constructor
• It does not implement thefinalize method
The EntityBean Interface
TheEntityBeaninterface extends theEnterpriseBeaninterface, which extendsthe Serializable interface The EntityBean interface declares a number ofmethods, such asejbActivateandejbLoad, which you must implement in yourentity bean class These methods are discussed later sections
Trang 15A B EAN -M ANAGED P ERSISTENCE E XAMPLE 85
The ejbCreate Method
When the client invokes a create method, the EJB container invokes the spondingejbCreatemethod Typically, anejbCreatemethod in an entity beanperforms the following tasks:
corre-• Inserts the entity state into the database
• Initializes the instance variables
• Returns the primary key
TheejbCreatemethod ofAccountEJBinserts the entity state into the database
by invoking the privateinsertRowmethod, which issues the SQLinsertment Here is the source code for the ejbCreate method in the AccountEJB
} try { insertRow(id, firstName, lastName, balance);
} catch (Exception ex) { throw new EJBException(“ejbCreate: “ + ex.getMessage());
} this.id = id;
Trang 1686 E NTITY B EANS
When writing anejbCreatemethod for an entity bean, be sure to follow theserules:
• The access control modifier must bepublic
• The return type must be the primary key (only for bean-managed tence)
persis-• The arguments must be legal types for Java RMI
• The method modifier cannot befinal orstatic
Thethrows clause may include the javax.ejb.CreateException and tions that are specific to your application AnejbCreatemethod usually throws
excep-a CreateException if an input parameter is invalid If an ejbCreate methodcannot create an entity because another entity with the same primary key alreadyexists, it should throw a javax.ejb.DuplicateKeyException (a subclass of
CreateException) If a client receives a CreateException or a cateKeyException, it should assume that the entity was not created
Dupli-The state of an entity bean may be directly inserted into the database by an cation that is unknown to the J2EE server For example, a SQL script mightinsert a row into themyaccounttable Although the entity bean for this row wasnot created by anejbCreate method, the bean can be located by a client pro-gram
appli-The ejbPostCreate Method
For eachejbCreatemethod, you must write anejbPostCreatemethod in theentity bean class The EJB container invokesejbPostCreateimmediately after
it callsejbCreate Unlike theejbCreatemethod, theejbPostCreatemethodcan invoke thegetPrimaryKeyandgetEJBObjectmethods of theEntityCon- textinterface For more information on thegetEJBObjectmethod, see Passing
an Enterprise Bean’s Object Reference (page 78) Often, your ejbPostCreate
methods will be empty
The signature of anejbPostCreate must meet the following requirements:
• The number and types of arguments must match a corresponding ate method
ejbCre-• The access control modifier must bepublic
• The method modifier cannot befinal orstatic
• The return type must bevoid.The throws clause may include the javax.ejb.CreateException and excep-tions that are specific to your application
Trang 17A B EAN -M ANAGED P ERSISTENCE E XAMPLE 87
The ejbRemove Method
A client removes an entity bean by invoking theremovemethod This invocationcauses the EJB client to call the ejbRemove method, which deletes the entitystate from the database The code for theejbRemovemethod in theAccountEJB
} }
If the ejbRemove method encounters a system problem, it should throw the
javax.ejb.EJBException If it encounters an application error, it should throw
a javax.ejb.RemoveException For a comparison of system and applicationexceptions, see the section, Handling Exceptions (page 115)
An entity bean may also be removed directly by a database deletion For ple, if a SQL script deletes a row that contains an entity bean state, then thatentity bean is removed
exam-The ejbLoad and ejbStore Methods
If the EJB container needs to synchronize the instance variables of an entity beanwith the corresponding values stored in a database, it invokes theejbLoadand
ejbStore methods TheejbLoad method refreshes the instance variables fromthe database, and theejbStoremethod writes the variables to the database Theclient may not callejbLoad andejbStore
If a business method is associated with a transaction, the container invokes Load before the business method executes Immediately after the businessmethod executes, the container calls ejbStore Because the container invokes
ejb-ejbLoadand ejbStore, you do not have to refresh and store the instance ables in your business methods—the container performs these functions for you
vari-TheAccountEJB class relies on the container to synchronize the instance ables with the database Therefore, the business methods ofAccountEJBshould
vari-be associated with transactions For instructions on setting transaction attributesfor methods, see the section, Running the New Enterprise BeanWizard (page 95)