外文翻译编写Bean管理持久性的实体Bean.docx

上传人:b****8 文档编号:11401805 上传时间:2023-02-28 格式:DOCX 页数:15 大小:24.84KB
下载 相关 举报
外文翻译编写Bean管理持久性的实体Bean.docx_第1页
第1页 / 共15页
外文翻译编写Bean管理持久性的实体Bean.docx_第2页
第2页 / 共15页
外文翻译编写Bean管理持久性的实体Bean.docx_第3页
第3页 / 共15页
外文翻译编写Bean管理持久性的实体Bean.docx_第4页
第4页 / 共15页
外文翻译编写Bean管理持久性的实体Bean.docx_第5页
第5页 / 共15页
点击查看更多>>
下载资源
资源描述

外文翻译编写Bean管理持久性的实体Bean.docx

《外文翻译编写Bean管理持久性的实体Bean.docx》由会员分享,可在线阅读,更多相关《外文翻译编写Bean管理持久性的实体Bean.docx(15页珍藏版)》请在冰豆网上搜索。

外文翻译编写Bean管理持久性的实体Bean.docx

外文翻译编写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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 初中教育 > 语文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1