2外文翻译编写容器管理持久性实体Bean.docx
《2外文翻译编写容器管理持久性实体Bean.docx》由会员分享,可在线阅读,更多相关《2外文翻译编写容器管理持久性实体Bean.docx(10页珍藏版)》请在冰豆网上搜索。
2外文翻译编写容器管理持久性实体Bean
WritingContainer-ManagedPersistentEntityBeans
Container-ManagedFields
Acontainer-managedpersistententitybeanallowsthecontainertohandlesomeorallofitsdataaccesslogic.RatherthancodingJDBCorSQL/Joperationsinyourbeanclass,yourcontainerimplicitlyperformsalldatabaseoperationsbehindthescenes.
Withcontainer-managedpersistence,youmustmakesomeofyourentitybeanclass’sfieldspublicsothatthecontainercansetthefieldswhenitperformsdatabaseoperationsonbehalfofyourbean.Thefieldsthatyouwanttobepersistentarecalledcontainer-managedfields.Youdon’thavetoworryaboutsettingthesefields—theEJBcontainerwillautomaticallymanipulatethemforyou
behindthesceneswhenitperformsstorageoperations.
Onerestrictionofcontainer-managedfieldsisthateveryfieldyouwanttobemanagedbythecontainermustfollowtherulesforJavaobjectserialization(wedescribetheserulesinfullinAppendixA).ThismeansthatprimitivetypessuchasdoublesandBooleans,aswellasserializableclassessuchasprimarykeyclassesorEJBhandlestootherentitybeans,canbecontainer-managedfields.
Forexample,thefollowingisasnippetofcodefromourbankaccountentitybeanclassthatwewroteinChapter8:
Withcontainer-managedpersistence,thecontainercanpersisteachofthesefieldsforyoubehindthescenes.Whensavingyourbeaninstance’sfields,thecontainerisresponsibleforqueryingyourbeaninstanceforthesefieldvalues.Whenloadingdataintoyourbeaninstance,thecontainersetsthesefields.Thisispossiblebecauseeachofthefieldsisdeclaredaspublic.
Ofcourse,youstillmustinformthecontaineraboutwhichfieldsitshouldmanipulate.Youspecifythisinyourbean’sdeploymentdescriptor.TheEJBcontainerwillinspectthedeploymentdescriptortofigureoutwhichofyourentitybean’sfieldstomanipulate.
Notethatnotallfieldswithinthebeanhavetobemanagedbythecontainer.Youmightbepullingdatamanuallyfromasecondarysource,oryoumighthavecalculatedfields.TheEJBcontainerwillautomaticallynotifyyourbeanclassduringpersistentoperations,allowingyoutomanagethesefields.
PrimaryKeyClass
Aswithbean-managedpersistence,container-managedpersistencedictatesthatyourprimarykeyclassmustbeserializable.BecausetheEJBcontainerwillworkwithyourprimarykey,therearenewrestrictionsforhowyouwriteyourprimarykeyclass.Themostimportantrestrictionisthatthefieldsyouhaveinyourprimarykeymustcomefromthecontainer-managedfieldsofyourentitybean,whichwedescribedpreviously.ThisrestrictionallowstheEJBcontainertoset,aswellasextract,yourentitybean’sprimarykeyfields.
Forexample,takeourprimarykeyclassfromourChapter8’sbankaccount:
Thisisavalidprimarykeyclassforcontainer-managedpersistencebecauseit’sserializableandbecauseitspublicfieldscomefromourbeanclass’scontainer-managedfields.
ImplementationGuidelinesforContainer-ManagedPersistence
Themethodimplementationsofyourentitybeansshouldbedifferentforcontainer-managedpersistententities.Nolongerareyoucontrollingtheroutinepersistentoperationsofyourbeans,andsomanyofthemethodscanbeleftempty—thecontainerwilldoitforyou.Table9.1isasummaryofwhatyoushouldimplementineachmethod,assumingyourentitybean’spersistenceiscontainermanaged.Takeaquickglanceatthechartfornow.Asyoucanseefromthetable,manyofthedatabase-intensiveoperationshavebeenreducedinscopesignificantly.Youshouldreferbacktothechartwhenreadingthroughthecodeinthischapterorwhenprogrammingyourownentitybeanclasses.Theorderofmethodslistedveryroughlymodelstheflowofcontrolofanentitybeaninstance’slifecyclethatwesawattheendofChapter7.
Container-ManagedPersistenceExample:
AProductLine
Let’sseeaquickdemonstrationofcontainer-managedpersistenceinaction,appliedtotheconceptofaproductline.
Ifyou’reworkingforaproduct-basedcompany,yourcompany’sproductlineisthesuiteofproductsyourcompanyoffers.Forexample,ifyou’reanappliancecompany,youmightofferadishwasher,astove,andadryer.Ifyou’reacomputerhardwarecompany,youmightoffermemory,harddisks,andprocessors.We’regoingtomodelagenericproductasanentitybeanthatusescontainer-managedpersistence.
TheobjectmodelforourproductlineisdetailedinFigure9.1.
Let’stakealookateachofthefilesthatwemustcreateforourentitybeancomponent.
Product.java
OurremoteinterfaceisspecifiedbyProduct.java,showninSource9.1.
OurremoteinterfaceisverysimilartoChapter8’sbankaccountremoteinterface.Ithasmethodstomodifytheentitybeaninstance’sfieldsandthrowsremoteexceptionstoindicatesystem-levelerrors.
ProductHome.java
Next,wehavetheproduct’shomeinterface,ProductHome.java,presentedinSource9.2
Ourhomeinterfacedefinesasinglecreate()methodtocreateanewproductinthedatabase.ItreturnsaProductEJBobjectsotheclientcanmanipulatetheentitybeandataandthrowsajavax.ejb.CreateExceptiontoindicateanapplication-levelproblem.
Wealsoexposeallsortsoffindermethodstofindexistingproducts.SomeofthefindersreturnasingleEJBobject,whileothersreturnajava.util.EnumerationofmultipleEJBobjects.Thisisneededifthefindermethodsfindmorethanonematchingobject.NotethatfindByPrimaryKey()shouldneverreturnanenumerationbecauseprimarykeysmustbeunique.
ProductPK.java
OurprimarykeyclassisdefinedbyProductPK.java,showninSource9.3.
AswithourBankAccount,ourprimarykeyisasimplestring.Andaswe’vefoundout,therearerestrictionsforwhatourprimarykeycanbe.Ourprimarykeyfieldsarecomingfromthecontainer-managedfieldsoftheentitybeanclass,asisrequiredwithcontainer-managedpersistence.Inparticular,ourprimarykeyrepresentstheIDstringofaproduct(suchasaproductSKUnumber).
ProductBean.java
Next,wehaveourcontainer-managedentitybeanimplementation,ProductBean.java,showninSource9.4.
Thisbeanismorecomplexthanourbankaccountexample.We’vedefinedmanyfindermethods,andwehavefourpersistentfields.Yeteventhoughwe’veaddedallthiscomplexity,ourbeanislessthan40percentofthesizeofourBankAccountbean.Thisisanamazingreductionincodecomplexity.Andbecauseourbeanhasnodatabasecodeinit,wehavereducedthechanceforbugsinourbeanthatwouldbeduetousererrorworkingwithJDBCcode.Thisisahugesavingsindevelopmentandtestingtime.
Wehavefourcontainer-managedfields,allwithpublicscope.They’republicsothatthecontainercanmanipulatethem.OurejbCreate()methodsimplysetsourcontainer-managedfieldstothepassed-inclientparameters.TheEJBcontainerwillextractthosefieldsandsetupthedatabasedataforus.NoticethatourejbCreate()methoddoesnotreturnaprimarykeybecausetheEJBcontainerdoesthatforus.
Therestofourbeanisjustemptymethodsandcomments.There’salmostnologicatall.Ourbeanclassisjustdatawithsomeaccessormethods.
Client.java
Ourclientcodeisasimplesuiteoftestcasestotryoutourbean,asshowninSource9.5.
WeperformaJNDIlookuptoacquirethehomeobjectandcreatesomeentitybeandata.Wethentryoutacoupleoffindermethods.Wecanloopthroughthefinders’returnednumerationsandcallbusinessmethodsoneachEJBobject.WethendestroyalltheEJBobjectswecreatedinafinally{}clause.
TheDeploymentDescriptor
Wenowneedtowriteourdeploymentdescriptor.Inadditiontodefiningthestandardentitybeanfields,wenowneedtoinformthecontaineraboutourpubliccontainer-managedfields.ThedeploymentdescriptorisshowninTable9.2.NoticethatwenolongerhaveanyJDBCapplication-specificpropertiesbecausewe’veexternalizedalldatabaseactivitytothecontainer.
Inadditiontothedeploymentdescriptor,weneedtotellthecontainerexactlyhowtoperformpersistentoperations.Thisisonetrade-offofcontainer-managedpersistence—youstillneedtodeclarepersistentrules,ratherthancodethemintoyourbeanusingJDBCorSQL/J.
Ifyou’reusingarelationaldatastore,you’llneedtodefineexactlyhowyourentitybean’spublicfieldsmaptothatdatabase.Thus,wemustdefineaseriesofobject-relationalmappingentries.Theseentriesmapentitybeanfieldstorelationaldatabasecolumnnames.TheEJBcontainer(inthiscase,BEAWebLogic)willusethismappingwhenstoringorretrievingourcontainer-managedfieldsfromthedatabase.NotethatthisisveryEJBcontainer-specific!
SomeEJBcontainerswillsupportobjectdatabasesandthuswillnothaveamappingintoatwo-dimensionalrelationaldatabase.ConsultyourEJBcontainer’sdocumentationformoreinformation.Ourproductline’spersistententriesforBEA’sWebLogicserverareshowninTable9.3.
Wealsoneedtospecifytheimplementationofourhomeobject’sfindermethods.Thisisalso,unfortunately,proprietaryforeachEJBcontainer.BEAWebLogichasasimplescriptinglanguageforthispurpose.Forexample:
ThecompletescriptisshowninTable9.4.Thecontainerwillimplementthislogic,perhapsusingJDBCorSQL/J.Wheneveraclientwantstoexecuteafindermethodonthehomeobject,thecontainerwillautomaticallyruntheimplementedJDBCorSQL/Jcode.
RunningtheClientProgram
Toruntheclientprogram,typeacommandsimilartothefollowing(dependingonwhatyourEJBcontainerJavaNamingandDirectoryInterface,orJNDI,initializationparametersare):
TheinitializationparametersarerequiredbyJNDItofindthehomeobject,aswelearnedin