Tải bản đầy đủ - 0 (trang)
Chapter 4. Developing Your First Enterprise Beans

Chapter 4. Developing Your First Enterprise Beans

Tải bản đầy đủ - 0trang

4.1ChoosingandSettingUpanEJBServer

TheEJBserveryouchooseshouldprovideautilityfordeploying

enterprisebeans.Itdoesn'tmatterwhethertheutilityis

command-lineorientedorgraphical,aslongasitdoesthejob.

Thedeploymentutilityshouldallowyoutoworkwith

prepackagedenterprisebeans,i.e.,enterprisebeansthathave

alreadybeendevelopedandarchivedinaJARfile.Finally,the

EJBservermustsupportanSQL-standardrelationaldatabase

thatisaccessibleusingJDBC.Forthedatabase,youshould

haveprivilegessufficientforcreatingandmodifyingafew

simpletablesinadditiontonormalread,update,anddelete

capabilities.IfyouhavechosenanEJBserverthatdoesnot

supportaSQL-standardrelationaldatabase,youmayneedto

modifytheexamplestoworkwiththeproductyouareusing.

Thisbookdoesnotsayverymuchabouthowtoinstalland

deployenterprisebeans.Thattaskislargelyserver-dependent.

We'llprovidesomegeneralideasabouthowtoorganizeJAR

filesandcreatedeploymentdescriptors,butforacomplete

descriptionofthedeploymentprocess,you'llhavetoreferto

yourvendor'sdocumentation.



4.1.1SettingUpYourJavaIDE

Togetthemostfromthischapter,ithelpstohaveanIDEthat

hasadebuggerandallowsyoutoaddJavafilestoits

environment.SeveralJavaIDEssuchasBEA'sWeblogic

Workshop,IBM'sEclipse,Borland'sJBuilder,andSun's

Fortefulfillthisrequirement.SomeEJBproducts,suchasIBM's

WebSphereandBEA'sWeblogic,aretightlycoupledwithanIDE

thatmakeslifealoteasierwhenitcomestowriting,deploying,

anddebuggingyourapplications.



OnceyouhaveanIDEsetup,youneedtoincludethe

EnterpriseJavaBeansandotherJ2EEpackageswhichwillbe

providedbyyourapplicationservervendorusuallyinasingle

JARfile(e.g.,j2ee.jar).



4.2DevelopinganEntityBean

There'snobetterplacetostartthantheCabinEJB,whichwe

havebeenexaminingthroughoutthepreviouschapters.The

CabinEJBisanentitybeanthatencapsulatesthedataand

behaviorassociatedwithacruiseshipcabininTitan'sbusiness

domain.



4.2.1Cabin:TheRemoteInterface

Whendevelopinganentitybean,wefirstwanttodefineits

remoteinterface.Theremoteinterfacedefinesthebean's

businesspurpose;themethodsofthisinterfacemustcapture

theconceptoftheentity.Wedefinedtheremoteinterfacefor

theCabinEJBinChapter2;here,weaddtwonewmethodsfor

settingandgettingtheshipIDandthebedcount.TheshipID

identifiestheshiptowhichthecabinbelongs,andthebed

counttellshowmanypeoplethecabincanaccommodate:

packagecom.titan.cabin;



importjava.rmi.RemoteException;



publicinterfaceCabinRemoteextendsjavax.ejb.EJBObject{

publicStringgetName()throwsRemoteException;

publicvoidsetName(Stringstr)throwsRemoteException;

publicintgetDeckLevel()throwsRemoteException;



publicvoidsetDeckLevel(intlevel)throwsRemoteException;

publicintgetShipId()throwsRemoteException;

publicvoidsetShipId(intsp)throwsRemoteException;

publicintgetBedCount()throwsRemoteException;

publicvoidsetBedCount(intbc)throwsRemoteException;

}



TheCabinRemoteinterfacedefinesfourproperties:name,

deckLevel,shipId,andbedCount.Propertiesareattributesof

anenterprisebeanthatcanbeaccessedbypublicsetandget

methods.

NoticethatwehavemadetheCabinRemoteinterfaceapartofa

newpackagenamedcom.titan.cabin.Placealltheclasses

andinterfacesassociatedwitheachtypeofbeaninapackage

specifictothebean.Becauseourbeansarefortheuseofthe

Titancruiseline,weplacedthesepackagesinthecom.titan

packagehierarchy.Wealsocreateddirectorystructuresthat

matchpackagestructures.IfyouareusinganIDEthatworks

directlywithJavafiles,createanewdirectorycalleddev(for

development)andcreatethedirectorystructureshownin

Figure4-1.CopytheCabinRemoteinterfaceintoyourIDEand

saveitsdefinitiontothecabindirectory.Compilethe

CabinRemoteinterfacetoensurethatitsdefinitioniscorrect.

TheCabinRemote.classfile,generatedbytheIDE'scompiler,

shouldbewrittentothecabindirectory,thesamedirectoryas

theCabinRemote.javafile.TherestoftheCabinbean'sclasses

willbeplacedinthissamedirectory.



Figure4-1.DirectorystructurefortheCabinbean



4.2.2CabinHome:TheRemoteHomeInterface

OncewehavedefinedtheremoteinterfaceoftheCabinEJB,we

havedefinedtheremoteviewofthissimpleentitybean.Next,

weneedtodefinetheCabinEJB'sremotehomeinterface,which

specifieshowtheenterprisebeancanbecreated,located,and

destroyedbyremoteclients;inotherwords,theCabinEJB's

life-cyclebehavior.Hereisacompletedefinitionofthe

CabinHomeRemotehomeinterface:

packagecom.titan.cabin;



importjava.rmi.RemoteException;

importjavax.ejb.CreateException;

importjavax.ejb.FinderException;



publicinterfaceCabinHomeRemoteextendsjavax.ejb.EJBHome{



publicCabinRemotecreate(Integerid)

throwsCreateException,RemoteException;



publicCabinRemotefindByPrimaryKey(Integerpk)

throwsFinderException,RemoteException;

}



TheCabinHomeRemoteinterfaceextendsjavax.ejb.EJBHome

anddefinestwolife-cyclemethods:create()and

findByPrimaryKey().Thesemethodscreateandlocate

remotereferencestoCabinEJBs.Removemethods(fordeleting

enterprisebeans)aredefinedinthejavax.ejb.EJBHome

interface,sotheCabinHomeRemoteinterfaceinheritsthem.



4.2.3CabinBean:TheBeanClass

Wehavenowdefinedtheremoteclient-sideAPIforcreating,

locating,using,andremovingtheCabinEJB.Nowweneedto

defineCabinBean,theclassthatprovidestheimplementation

ontheserverfortheCabinEJB.TheCabinBeanclassisan

entitybeanthatusescontainer-managedpersistence,soits

definitionwillbefairlysimple.



InadditiontothecallbackmethodsdiscussedinChapter2and

Chapter3,wemustalsodefineaccessormethodsforthe

CabinRemoteinterfaceandanimplementationofthecreate

methoddefinedintheCabinHomeRemoteinterface.Hereisthe

completedefinitionoftheCabinBeanclass:

packagecom.titan.cabin;



importjavax.ejb.EntityContext;



publicabstractclassCabinBeanimplementsjavax.ejb.EntityBean



publicIntegerejbCreate(Integerid){

this.setId(id);

returnnull;

}

publicvoidejbPostCreate(Integerid){



}

publicabstractvoidsetId(Integerid);

publicabstractIntegergetId();





publicabstractvoidsetShipId(intship);

publicabstractintgetShipId();



publicabstractvoidsetName(Stringname);

publicabstractStringgetName();



publicabstractvoidsetBedCount(intcount);

publicabstractintgetBedCount();



publicabstractvoidsetDeckLevel(intlevel);

publicabstractintgetDeckLevel();



publicvoidsetEntityContext(EntityContextctx){

//Emptyimplementation.

}

publicvoidunsetEntityContext(){

//Emptyimplementation.

}



publicvoidejbActivate(){

//Emptyimplementation.

}

publicvoidejbPassivate(){

//Emptyimplementation.

}

publicvoidejbLoad(){

//Emptyimplementation.

}

publicvoidejbStore(){

//Emptyimplementation.

}

publicvoidejbRemove(){

//Emptyimplementation.

}

}



TheCabinBeanclasscanbedividedintotwosectionsfor

discussion:declarationsforthecontainer-managedfieldsand

thecallbackmethods.



4.2.3.1Container-managedfields

TheCabinBeandefinesseveralpairsofabstractaccessor

methods.Forexample,setName()andgetName()areapair

ofabstractaccessormethods.Thesemethodsareresponsible

forsettingandgettingtheentitybean'snamefield.Whenthe

beanisdeployed,theEJBcontainerautomaticallyimplements

alltheabstractaccessormethodssothatthebeanstatecanbe

synchronizedwiththedatabase.Theseimplementationsmap

theabstractaccessormethodstofieldsinthedatabase.

Althoughalltheabstractaccessormethodshavecorresponding

methodsintheremoteinterface,CabinRemote,it'snot

necessarythattheydoso.Someaccessormethodsareforthe

entitybean'suseonlyandareneverexposedtotheclient

throughtheremoteorlocalinterfaces.Notethat,unlikethe

matchingmethodsintheremoteinterface,theabstract

accessormethodsdonotthrowRemoteExceptions.

It'scustomarytoconsidertheabstractaccessormethodsas

providingaccesstovirtualfieldsandtorefertothosefieldsby

theirmethodnames,lessthegetorsetprefix.Forexample,

thegetName()/setName()abstractaccessormethodsdefine

avirtualcontainer-managedpersistence(CMP)fieldcalledname

(thefirstletterisalwayschangedtolowercase).The

getDeckLevel()/setDeckLevel()abstractaccessormethods

defineavirtualCMPfieldcalleddeckLevel,andsoon.

Thename,deckLevel,shipId,andbedCountfieldsrepresent

theCabinEJB'spersistentstate.Theywillbemappedtothe

databaseatdeploymenttime.Thesefieldsarealsopublicly

availablethroughtheentitybean'sremoteinterface.Invoking

thegetBedCount()methodonaCabinRemoteEJBobject

causesthecontainertodelegatethatcalltothecorresponding

getBedCount()methodontheCabinBeaninstance.

ThereisnorequirementthatCMPfieldsmustbeexposed.The



idfieldisanothercontainer-managedfield,butitsabstract

accessormethodsarenotexposedtotheclientthroughthe

CabinRemoteinterface.Thisfieldistheprimarykeyofthe

CabinEJB;it'stheentitybean'sindextoitsdatainthe

database.It'sbadpracticetoexposetheprimarykeyofan

entitybeanyoudon'twantclientapplicationstobeableto

changethatkey.



4.2.3.2Thecallbackmethods

TheCabinHomeRemoteinterfacedefinesonecreate()method,

sothereisonlyonecorrespondingejbCreate()methodand

oneejbPostCreate()methoddefinedbytheCabinBeanclass.

Whenaclientinvokesthecreate()methodontheremote

homeinterface,itisdelegatedtoamatchingejbCreate()

methodontheentitybeaninstance.TheejbCreate()method

initializesthefields;inthecaseoftheCabinBean,itsetstheid

field.



Althoughit'snotrequiredbytheEJBspecification,someJ2EE

applicationvendorsinsistthatejbCreate()throwa

javax.ejb.CreateExceptionthisistrueoftheJ2EE1.4SDK.Thishas

neverbeenarequirement,butit'sanissuethatcontinuestocropup

everytimethereisaneweditionofthisbook.



TheejbCreate()methodalwaysreturnstheprimarykey

type;withcontainer-managedpersistence,thismethodreturns

thenullvalue.It'sthecontainer'sresponsibilitytocreatethe

primarykey.Whydoesitreturnnull?Thisconventionmakesit

easierforEJBvendorsthatsupportcontainer-managed

persistenceusingbean-managedpersistenceit'satechnique

thatismorecommoninEJB1.1.Bean-managedpersistence



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. Developing Your First Enterprise Beans

Tải bản đầy đủ ngay(0 tr)

×