外文翻译编写Bean管理持久性的实体Bean.docx
- 文档编号:6138631
- 上传时间:2023-05-09
- 格式:DOCX
- 页数:15
- 大小:24.84KB
外文翻译编写Bean管理持久性的实体Bean.docx
《外文翻译编写Bean管理持久性的实体Bean.docx》由会员分享,可在线阅读,更多相关《外文翻译编写Bean管理持久性的实体Bean.docx(15页珍藏版)》请在冰点文库上搜索。
外文翻译编写Bean管理持久性的实体Bean
CHAPTER8WritingBean-ManagedPersistentEntityBeans
InChapter7,wecoveredsomebasicentitybeanconcepts.Welearnedthattherearetwokindsofentitybeans—bean-managedpersistentandcontainer-managedpersistent.
Inthischapter,we’lldemonstratehowtoprogrambean-managedpersistententitybeans.Whenyoucodethesetypesofentitybeans,youmustprovideyourowndataaccesslogic.Youareresponsibleforprovidingtheimplementationtomapyourentitybeaninstancestoandfromstorage.Todothis,you’dtypically.useadatabaseAPIsuchasJDBCorSQL/J.Thisisinstarkcontrasttocontainer-managedpersistententitybeans,whichhavetheirdataaccesshandledforthembytheEJBcontainer.Thischapterwillteachyouthebasicsofbean-managedpersistenceandshowyouhowtobuildasimplebean-managedentitybeanusingJDBC.
ImplementationGuidelinesforBean-ManagedPersistence
InChapter7,wesawthatallentitybeanclasses—bothbean-managedpersistentandcontainer-managedpersistent—mustimplementthejavax.ejb.EntityBeaninterface.Thisinterfacedefinescallbackmethodsthatthecontainerinvokesonyourbeans.Whatyoushouldputinthesemethodsdependsinpartonwhetheryouareusingbean-managedpersistenceorcontainer-managedpersistence.Table8.1isasummaryofwhatyoushouldimplementineachmethod,assumingyourentitybean’spersistenceisbean-managed.Takeaquickglanceatthe.
Table8.1DescriptionsandImplementationGuidelinesforBean-ManagedPersistentEntities.
chartfornow.Youshouldreferbacktothechartwhenreadingthroughthecodeinthischapterorwhenprogrammingyourownentitybeanclasses.Theorderofmethodslistedveryroughlymodelstheflowofcontrolofanentitybeaninstance’slifecyclethatwesawattheendofChapter7.
Bean-ManagedPersistenceExample:
ABankAccount
Ourfirstexamplewillbeasimplebankaccountentitybean.Thisbankaccountbeancanbeusedtorepresentandmanipulaterealbankaccountdatainanunderlyingrelationaldatabase.
TheobjectmodelforourbankaccountisdetailedinFigure8.1.
Let’stakealookateachofthefilesthatwemustcreateforourentitybeancomponent.
Figure8.1Thebankaccountobjectmodel.
Account.java
Account.javaisourentitybean’sremoteinterface—whattheclientsees.It’sshowninSource8.1.
Noticethattheaccountremoteinterfaceextendsjavax.ejb.EJBObject,whichallremoteinterfacesmustdo.Ourinterfaceexposesanumberofmethodsformanipulatingentitybeans,suchasformakingdepositsandwithdrawals.Allofourmethodsthrowremoteexceptionstofacilitatesystem-levelcatastrophic.
Source8.1Account.java.
failures.Noticethatinourwithdrawalmethod,wealsothrowourowncustomapplication-levelexception,AccountException.We’lldefinethatexceptionbitlater.
AccountHome.java
OurhomeinterfaceisspecifiedbyAccountHome.java,showninSource8.2.
Source8.2AccountHome.java(continued).
Weprovideonemethodtocreateanewaccount.Thiswillcreatenewdatabasedatarepresentingabankaccount.ItreturnsanEJBobjecttotheclientsothattheclientcanmanipulatethatnewlycreatedaccount.Noticethatwethrowtheapplication-leveljavax.ejb.CreateException,whichallcreate()methodsmustthrow.
Wealsohavetwofindermethods.findByPrimaryKey()searchesthedatabaseforabankaccountthatalreadyexists;itsearchesbytheaccountID,whichwewilldefinebelowinAccountPK.java.Wealsohaveacustomfindermethod,findByOwnerName(),whichsearchesthedatabaseforallbankaccountsthathavethesameowner’sname.Becausewe’reusingbean-managedpersistence.we’llneedtoimplementbothofthesefindermethodsinourentitybeanimplementation(ifwewereusingcontainer-managedpersistence,thecontainerwouldsearchthedatabaseforus).Aswithourcreatemethod,bothfindersreturnEJBobjectssothattheclientcanmanipulatethenewlyfoundbankaccounts.Wethrowtheapplication-leveljavax.ejb.FinderException,whichallfindersmustthrow.
AccountPK.java
Ourentitybean’sprimarykeyclassisdefinedbyAccountPK.java,detailedinSource8.3.
Ourprimarykeyisasimplestring—theaccountIDstring.Forexample,anaccountIDstringcouldbe“ABC-123-0000.”Thisstringmustbeuniquetoitsbankaccount—werelyontheclientcodethatconstructsouraccountIDtomakesureit’sunique.Theprimarykeyisusedtoidentifyeachbankaccountuniquely.
AccountBean.java
Next,wehaveourentitybeanimplementationclass,AccountBean.java.Ourbeanimplementationcodeisquitelengthy,anditisdividedintoseveralsections:
Bean-managedstatefields.
Thesearethepersistablefieldsofourentitybeanclass.Ourbeaninstancewillloadandstorethedatabasedataintothesefields.
Source8.3AccountPK.java.
Businesslogicmethods.
Thesemethodsperformservicesforclients,suchaswithdrawingordepositingintoanaccount.Theyareexposedbytheremoteinterface,Account.
EJB-requiredmethods.
TheseareEJB-requiredmethodsthatthecontainerwillcalltomanageourbean.Theyalsoincludeourcreatorandfindermethodsdefinedinthehomeinterface.
ThecodeispresentedinSource8.4.Noticehowcumbersomethecodeis—justforasimplebankaccount.Thisisanunfortunatedrawbackofbean-managedpersistencebecauseyoumustprovidealldataaccesscode.
NoticethatmostofthelogicinourbeanisJDBCcode.Ourwithdrawanddepositmethodssimplymodifythein-memoryfieldsoftheentitybeaninstance.Iftheclienttriestowithdrawfromanegativeaccount,wethrowourcustomapplication-levelexception,AccountException.Wheneverweperformpersistentoperations,weretrieveaJDBCconnectionviathegetConnection()method.
WeacquireourenvironmentinformationfromtheEntityContextbycallinggetEnvironment().WethenusethatenvironmentasaparametertotheJDBCDriverManager’sgetConnection()method.ThisenvironmentspecifiestheJDBCdriverstoload,viathejdbc.driversproperty.WespecifythispropertyintheSource8.4AccountBean.java(continues).
application-specificenvironmentpropertiesthatshipwithourbean,aswe’llseeveryshortly.WealsospecifytheparticulardatabasetoconnecttoviaapropertywecallJDBC_URL.ThispropertyispassedtotheDriverManageraswell,soitknowswithwhichdatabasetohookup.
Inourbankaccountexample,weretrieveourJDBCconnectionsviatheJDBCcallDriverManager.getConnection().Wealsocloseeachconnectionaftereverymethodcall.ThisallowsourEJBcontainertopoolJDBCconnections.Whentheconnectionisnotinuse,anotherbeancanuseourconnection.
AlthoughthisworkswithBEAWebLogicserver,itisnotastandard,portablewayforconnectionpooling.WebLogicperformspoolingdirectlybeneaththeJDBC1.0drivershell,butotherEJBvendorsmayrequiredifferentmechanismsforpoolingdatabaseconnections.ConnectionpoolingisunfortunatelynotspecifiedbyJDBC1.0,whichmeansthatanyenterprisebeansthatuseJDBC1.0arenotveryportable.
Thereisalightattheendofthetunnel.ThenewJDBC2.0specification,whichhasbeenfinalized,supportsaportablemechanismofdatabaseconnectionpooling.AlreadyvendorsarebeginningtosupportJDBC2.0,andbythetimeyoureadthis,mosteveryseriousrelationaldatabasevendorshouldhaveaJDBC2.0driver.TheJava2Platform,EnterpriseEdition(J2EE)specificationmandatessupportofJDBC2.0aswell,whichisgoodnewsforanyonewritingtoJ2EEandtheEJB1.1specification.Furthermore,EJB1.1specifiesaportablewaytoretrieveaJDBCdriverthroughtheJavaNamingandDirectoryInterface(JNDI),whichwedetailinAppendixD.
OurfindermethodsuseJDBCtoperformSELECTstatementsontherelationaldatabasetoqueryforbankaccountrecords.Wecreateanewprimarykeyclassforthedatawefind,andwereturntheprimarykeytothecontainer.ThecontainerwilltheninstantiateEJBobjectsthatmatcheachprimarykey,sothattheclientscanstartworkingwiththedata.
Tocreateanewbankaccount,theclientcallscreate()onthehomeobject,whichcallsourejbCreate()andejbPostCreate()methods.NoticethatweinsertsomedataintothedatabaseusingJDBCinejbCreate().Wealsoassignourmembervariablesthedatapassedinfromtheclient.Wedon’tneedtouseejbPostCreate()foranything.Ourentitybeanisnowassociatedwithsomespecificdatabasedataandisassociatedwithaclient-specificEJBobject.
Noticethatwedon’tholdanybean-independentresources,sooursetEntity-Context()andunsetEntityContext()methodsarefairlybare-boned.Wealsodon’tholdanybean-specificresources,soourejbPassivate()andejbActivate()methodsareempty.
Whenthecontainersynchronizesourbeanwiththedatabase,theejbLoad()andejbStore()methodsperformJDBCpersistence,thuskeepingeveryone’sdatainsynch.NoticethatejbLoad()acquirestheprimarykeyviaagetPrimaryKey()calltotheEntityContext.Thisishowitfiguresoutwhatdatatoload.
JDBCcanbeverytoughtodebugduetoincompatibilitiesbetweendatabases.It’smucheasiertodebugJDBCifyoulogwhatJDBCisdoingbehindthescenes.Todothis,seethecommentedcodeinthegetConnection()methodofAccountBean.java.Simplyuncommentthoselinestoenablelogging.
AccountException.java
OurcustomexceptionclassisAccountException.java,displayedinSource8.5.Itsimplydelegatestotheparentjava.lang.Exceptionclass.It’sstillusefultodefineourowncustomexceptionclass,however,sothatwecandistinguishbetweenaproblemwithourbankaccountcomponent,andaproblemwithanotherpartofadeployedsystem.
Source8.5AccountException.java.
Client.java
OurlastJavafileisasimpletestclienttoexerciseourb
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 外文翻译 编写Bean管理持久性的实体Bean 外文 翻译 编写 Bean 管理 持久性 实体