|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
先谈谈我对java的一些认识。我选择java,是因为他语法简单,功能强大,从web,到桌面,到嵌入式,无所不能。但当我进一步了解了java后,感叹,java原来也有许多缺点。enterprise|j2eeEnterprisebeansaretheJ2EEcomponentsthatimplementEnterpriseJavaBeans(EJB)technology.EnterprisebeansrunintheEJBcontainer,aruntimeenvironmentwithintheJ2EEserver(seeFigure1-5).Althoughtransparenttotheapplicationdeveloper,theEJBcontainerprovidessystem-levelservicessuchastransactionstoitsenterprisebeans.Theseservicesenableyoutoquicklybuildanddeployenterprisebeans,whichformthecoreoftransactionalJ2EEapplications.WhatIsanEnterpriseBean?
WrittenintheJavaprogramminglanguage,anenterprisebeanisaserver-sidecomponentthatencapsulatesthebusinesslogicofanapplication.Thebusinesslogicisthecodethatfulfillsthepurposeoftheapplication.Inaninventorycontrolapplication,forexample,theenterprisebeansmightimplementthebusinesslogicinmethodscalledcheckInventoryLevelandorderProduct.Byinvokingthesemethods,remoteclientscanaccesstheinventoryservicesprovidedbytheapplication.BenefitsofEnterpriseBeans
Forseveralreasons,enterprisebeanssimplifythedevelopmentoflarge,distributedapplications.First,becausetheEJBcontainerprovidessystem-levelservicestoenterprisebeans,thebeandevelopercanconcentrateonsolvingbusinessproblems.TheEJBcontainer--notthebeandeveloper--isresponsibleforsystem-levelservicessuchastransactionmanagementandsecurityauthorization.Second,becausethebeans--andnottheclients--containtheapplicationsbusinesslogic,theclientdevelopercanfocusonthepresentationoftheclient.Theclientdeveloperdoesnothavetocodetheroutinesthatimplementbusinessrulesoraccessdatabases.Asaresult,theclientsarethinner,abenefitthatisparticularlyimportantforclientsthatrunonsmalldevices.Third,becauseenterprisebeansareportablecomponents,theapplicationassemblercanbuildnewapplicationsfromexistingbeans.TheseapplicationscanrunonanycompliantJ2EEserver.WhentoUseEnterpriseBeans
Youshouldconsiderusingenterprisebeansifyourapplicationhasanyofthefollowingrequirements:
- Theapplicationmustbescalable.Toaccommodateagrowingnumberofusers,youmayneedtodistributeanapplicationscomponentsacrossmultiplemachines.Notonlycantheenterprisebeansofanapplicationrunondifferentmachines,buttheirlocationwillremaintransparenttotheclients.
- Transactionsarerequiredtoensuredataintegrity.Enterprisebeanssupporttransactions,themechanismsthatmanagetheconcurrentaccessofsharedobjects.
- Theapplicationwillhaveavarietyofclients.Withjustafewlinesofcode,remoteclientscaneasilylocateenterprisebeans.Theseclientscanbethin,various,andnumerous.
TypesofEnterpriseBeans
Table3-1summarizesthethreedifferenttypesofenterprisebeans.Thefollowingsectionsdiscusseachtypeinmoredetail.<Palign=center>Table3-1SummaryofEnterpriseBeanTypes<Palign=center>EnterpriseBeanType<Palign=center>Purpose<Palign=left>Session<Palign=left>Performsataskforaclient<Palign=left>Entity<Palign=left>Representsabusinessentityobjectthatexistsinpersistentstorage<Palign=left>Message-Driven<Palign=left>ActsasalistenerfortheJavaMessageServiceAPI,processingmessagesasynchronouslyWhatIsaSessionBean?
AsessionbeanrepresentsasingleclientinsidetheJ2EEserver.Toaccessanapplicationthatisdeployedontheserver,theclientinvokesthesessionbeansmethods.Thesessionbeanperformsworkforitsclient,shieldingtheclientfromcomplexitybyexecutingbusinesstasksinsidetheserver.Asitsnamesuggests,asessionbeanissimilartoaninteractivesession.Asessionbeanisnotshared--itmayhavejustoneclient,inthesamewaythataninteractivesessionmayhavejustoneuser.Likeaninteractivesession,asessionbeanisnotpersistent.(Thatis,itsdataisnotsavedtoadatabase.)Whentheclientterminates,itssessionbeanappearstoterminateandisnolongerassociatedwiththeclient.Forcodesamples,seeChapter4.StateManagementModes
Therearetwotypesofsessionbeans:statefulandstateless.StatefulSessionBeans
Thestateofanobjectconsistsofthevaluesofitsinstancevariables.Inastatefulsessionbean,theinstancevariablesrepresentthestateofauniqueclient-beansession.Becausetheclientinteracts("talks")withitsbean,thisstateisoftencalledtheconversationalstate.Thestateisretainedforthedurationoftheclient-beansession.Iftheclientremovesthebeanorterminates,thesessionendsandthestatedisappears.Thistransientnatureofthestateisnotaproblem,however,becausewhentheconversationbetweentheclientandthebeanendsthereisnoneedtoretainthestate.StatelessSessionBeans
Astatelesssessionbeandoesnotmaintainaconversationalstateforaparticularclient.Whenaclientinvokesthemethodofastatelessbean,thebeansinstancevariablesmaycontainastate,butonlyforthedurationoftheinvocation.Whenthemethodisfinished,thestateisnolongerretained.Exceptduringmethodinvocation,allinstancesofastatelessbeanareequivalent,allowingtheEJBcontainertoassignaninstancetoanyclient.Becausestatelesssessionbeanscansupportmultipleclients,theycanofferbetterscalabilityforapplicationsthatrequirelargenumbersofclients.Typically,anapplicationrequiresfewerstatelesssessionbeansthanstatefulsessionbeanstosupportthesamenumberofclients.Attimes,theEJBcontainermaywriteastatefulsessionbeantosecondarystorage.However,statelesssessionbeansareneverwrittentosecondarystorage.Therefore,statelessbeansmayofferbetterperformancethanstatefulbeans.WhentoUseSessionBeans
Ingeneral,youshoulduseasessionbeanifthefollowingcircumstanceshold:
- Atanygiventime,onlyoneclienthasaccesstothebeaninstance.
- Thestateofthebeanisnotpersistent,existingonlyforashortperiodoftime(perhapsafewhours).
Statefulsessionbeansareappropriateifanyofthefollowingconditionsaretrue:
- Thebeansstaterepresentstheinteractionbetweenthebeanandaspecificclient.
- Thebeanneedstoholdinformationabouttheclientacrossmethodinvocations.
- Thebeanmediatesbetweentheclientandtheothercomponentsoftheapplication,presentingasimplifiedviewtotheclient.
- Behindthescenes,thebeanmanagestheworkflowofseveralenterprisebeans.Foranexample,seetheAccountControllerEJBsessionbeaninChapter18.
Toimproveperformance,youmightchooseastatelesssessionbeanifithasanyofthesetraits:
- Thebeansstatehasnodataforaspecificclient.
- Inasinglemethodinvocation,thebeanperformsagenerictaskforallclients.Forexample,youmightuseastatelesssessionbeantosendane-mailthatconfirmsanonlineorder.
- Thebeanfetchesfromadatabaseasetofread-onlydatathatisoftenusedbyclients.Suchabean,forexample,couldretrievethetablerowsthatrepresenttheproductsthatareonsalethismonth.
WhatIsanEntityBean?
Anentitybeanrepresentsabusinessobjectinapersistentstoragemechanism.Someexamplesofbusinessobjectsarecustomers,orders,andproducts.IntheJ2EESDK,thepersistentstoragemechanismisarelationaldatabase.Typically,eachentitybeanhasanunderlyingtableinarelationaldatabase,andeachinstanceofthebeancorrespondstoarowinthattable.Forcodeexamplesofentitybeans,pleaserefertochapters5and6.WhatMakesEntityBeansDifferentfromSessionBeans?
Entitybeansdifferfromsessionbeansinseveralways.Entitybeansarepersistent,allowsharedaccess,haveprimarykeys,andmayparticipateinrelationshipswithotherentitybeans.Persistence
Becausethestateofanentitybeanissavedinastoragemechanism,itispersistent.PersistencemeansthattheentitybeansstateexistsbeyondthelifetimeoftheapplicationortheJ2EEserverprocess.Ifyouveworkedwithdatabases,yourefamiliarwithpersistentdata.Thedatainadatabaseispersistentbecauseitstillexistsevenafteryoushutdownthedatabaseserverortheapplicationsitservices.Therearetwotypesofpersistenceforentitybeans:bean-managedandcontainer-managed.Withbean-managedpersistence,theentitybeancodethatyouwritecontainsthecallsthataccessthedatabase.Ifyourbeanhascontainer-managedpersistence,theEJBcontainerautomaticallygeneratesthenecessarydatabaseaccesscalls.Thecodethatyouwritefortheentitybeandoesnotincludethesecalls.Foradditionalinformation,seethesectionContainer-ManagedPersistence.SharedAccess
Entitybeansmaybesharedbymultipleclients.Becausetheclientsmightwanttochangethesamedata,itsimportantthatentitybeansworkwithintransactions.Typically,theEJBcontainerprovidestransactionmanagement.Inthiscase,youspecifythetransactionattributesinthebeansdeploymentdescriptor.Youdonothavetocodethetransactionboundariesinthebean--thecontainermarkstheboundariesforyou.SeeChapter14formoreinformation.PrimaryKey
Eachentitybeanhasauniqueobjectidentifier.Acustomerentitybean,forexample,mightbeidentifiedbyacustomernumber.Theuniqueidentifier,orprimarykey,enablestheclienttolocateaparticularentitybean.FormoreinformationseethesectionPrimaryKeysforBean-ManagedPersistence.Relationships
Likeatableinarelationaldatabase,anentitybeanmayberelatedtootherentitybeans.Forexample,inacollegeenrollmentapplication,StudentEJBandCourseEJBwouldberelatedbecausestudentsenrollinclasses.Youimplementrelationshipsdifferentlyforentitybeanswithbean-managedpersistenceandthosewithcontainer-managedpersistence.Withbean-managedpersistence,thecodethatyouwriteimplementstherelationships.Butwithcontainer-managedpersistence,theEJBcontainertakescareoftherelationshipsforyou.Forthisreason,relationshipsinentitybeanswithcontainer-managedpersistenceareoftenreferredtoascontainer-managedrelationships.Container-ManagedPersistence
Thetermcontainer-managedpersistencemeansthattheEJBcontainerhandlesalldatabaseaccessrequiredbytheentitybean.Thebeanscodecontainsnodatabaseaccess(SQL)calls.Asaresult,thebeanscodeisnottiedtoaspecificpersistentstoragemechanism(database).Becauseofthisflexibility,evenifyouredeploythesameentitybeanondifferentJ2EEserversthatusedifferentdatabases,youwontneedtomodifyorrecompilethebeanscode.Inshort,yourentitybeansaremoreportable.Inordertogeneratethedataaccesscalls,thecontainerneedsinformationthatyouprovideintheentitybeansabstractschema.AbstractSchema
Partofanentitybeansdeploymentdescriptor,theabstractschemadefinesthebeanspersistentfieldsandrelationships.Thetermabstractdistinguishesthisschemafromthephysicalschemaoftheunderlyingdatastore.Inarelationaldatabase,forexample,thephysicalschemaismadeupofstructuressuchastablesandcolumns.Youspecifythenameofanabstractschemainthedeploymentdescriptor.ThisnameisreferencedbyquerieswrittenintheEnterpriseJavaBeansQueryLanguage("EJBQL").Foranentitybeanwithcontainer-managedpersistence,youmustdefineanEJBQLqueryforeveryfindermethod(exceptfindByPrimaryKey).TheEJBQLquerydeterminesthequerythatisexecutedbytheEJBcontainerwhenthefindermethodisinvoked.TolearnmoreaboutEJBQL,seeChapter8.Youllprobablyfindithelpfultosketchtheabstractschemabeforewritinganycode.Figure3-1representsasimpleabstractschemathatdescribestherelationshipsbetweenthreeentitybeans.Theserelationshipsarediscussedfurtherinthesectionsthatfollow.<P>Figure3-1AHigh-LevelViewofanAbstractSchemaPersistentFields
Thepersistentfieldsofanentitybeanarestoredintheunderlyingdatastore.Collectively,thesefieldsconstitutethestateofthebean.Atruntime,theEJBcontainerautomaticallysynchronizesthisstatewiththedatabase.Duringdeployment,thecontainertypicallymapstheentitybeantoadatabasetableandmapsthepersistentfieldstothetablescolumns.ACustomerEJBentitybean,forexample,mighthavepersistentfieldssuchasfirstName,lastName,phone,andemailAddress.Incontainer-managedpersistence,thesefieldsarevirtual.Youdeclarethemintheabstractschema,butyoudonotcodethemasinstancevariablesintheentitybeanclass.Instead,thepersistentfieldsareidentifiedinthecodebyaccessmethods(gettersandsetters).RelationshipFields
Arelationshipfieldislikeaforeignkeyinadatabasetable--itidentifiesarelatedbean.Likeapersistentfield,arelationshipfieldisvirtualandisdefinedintheenterprisebeanclasswithaccessmethods.Butunlikeapersistentfield,arelationshipfielddoesnotrepresentthebeansstate.RelationshipfieldsarediscussedfurtherinDirectioninContainer-ManagedRelationships.MultiplicityinContainer-ManagedRelationships
Therearefourtypesofmultiplicities:One-to-one:Eachentitybeaninstanceisrelatedtoasingleinstanceofanotherentitybean.Forexample,tomodelaphysicalwarehouseinwhicheachstoragebincontainsasinglewidget,StorageBinEJBandWidgetEJBwouldhaveaone-to-onerelationship.One-to-many:Anentitybeaninstancemayberelatedtomultipleinstancesoftheotherentitybean.Asalesorder,forexample,canhavemultiplelineitems.Intheorderapplication,OrderEJBwouldhaveaone-to-manyrelationshipwithLineItemEJB.Many-to-one:Multipleinstancesofanentitybeanmayberelatedtoasingleinstanceoftheotherentitybean.Thismultiplicityistheoppositeofaone-to-manyrelationship.Intheexamplementionedinthepreviousitem,fromtheperspectiveofLineItemEJBtherelationshiptoOrderEJBismany-to-one.Many-to-many:Theentitybeaninstancesmayberelatedtomultipleinstancesofeachother.Forexample,incollegeeachcoursehasmanystudents,andeverystudentmaytakeseveralcourses.Therefore,inanenrollmentapplication,CourseEJBandStudentEJBwouldhaveamany-to-manyrelationship.DirectioninContainer-ManagedRelationships
Thedirectionofarelationshipmaybeeitherbidirectionalorunidirectional.Inabidirectionalrelationship,eachentitybeanhasarelationshipfieldthatreferstotheotherbean.Throughtherelationshipfield,anentitybeanscodecanaccessitsrelatedobject.Ifanentitybeanhasarelativefield,thenweoftensaythatit"knows"aboutitsrelatedobject.Forexample,ifOrderEJBknowswhatLineItemEJBinstancesithasandifLineItemEJBknowswhatOrderEJBitbelongsto,thentheyhaveabidirectionalrelationship.Inaunidirectionalrelationship,onlyoneentitybeanhasarelationshipfieldthatreferstotheother.Forexample,LineItemEJBwouldhavearelationshipfieldthatidentifiesProductEJB,butProductEJBwouldnothavearelationshipfieldforLineItemEJB.Inotherwords,LineItemEJBknowsaboutProductEJB,butProductEJBdoesntknowwhichLineItemEJBinstancesrefertoit.EJBQLqueriesoftennavigateacrossrelationships.Thedirectionofarelationshipdetermineswhetheraquerycannavigatefromonebeantoanother.Forexample,aquerycannavigatefromLineItemEJBtoProductEJB,butcannotnavigateintheoppositedirection.ForOrderEJBandLineItemEJB,aquerycouldnavigateinbothdirections,sincethesetwobeanshaveabidirectionalrelationship.WhentoUseEntityBeans
Youshouldprobablyuseanentitybeanunderthefollowingconditions:
- Thebeanrepresentsabusinessentity,notaprocedure.Forexample,CreditCardEJBwouldbeanentitybean,butCreditCardVerifierEJBwouldbeasessionbean.
- Thebeansstatemustbepersistent.IfthebeaninstanceterminatesoriftheJ2EEserverisshutdown,thebeansstatestillexistsinpersistentstorage(adatabase).
WhatIsaMessage-DrivenBean?
Note:ThissectioncontainstextfromTheJavaMessageServiceTutorial.Becausemessage-drivenbeansrelyonJavaMessageService(JMS)technology,tofullyunderstandhowthesebeansworkyoushouldconsultthetutorialatthisURL:http://java.sun.com/products/jms/tutorial/index.htmlAmessage-drivenbeanisanenterprisebeanthatallowsJ2EEapplicationstoprocessmessagesasynchronously.ItactsasaJMSmessagelistener,whichissimilartoaneventlistenerexceptthatitreceivesmessagesinsteadofevents.ThemessagesmaybesentbyanyJ2EEcomponent--anapplicationclient,anotherenterprisebean,oraWebcomponent--orbyaJMSapplicationorsystemthatdoesnotuseJ2EEtechnology.Message-drivenbeanscurrentlyprocessonlyJMSmessages,butinthefuturetheymaybeusedtoprocessotherkindsofmessages.Foracodesample,seeChapter7.WhatMakesMessage-DrivenBeansDifferentfromSessionandEntityBeans?
Themostvisibledifferencebetweenmessage-drivenbeansandsessionandentitybeansisthatclientsdonotaccessmessage-drivenbeansthroughinterfaces.InterfacesaredescribedinthesectionDefiningClientAccesswithInterfaces.Unlikeasessionorentitybean,amessage-drivenbeanhasonlyabeanclass.Inseveralrespects,amessage-drivenbeanresemblesastatelesssessionbean.
- Amessage-drivenbeansinstancesretainnodataorconversationalstateforaspecificclient.
- Allinstancesofamessage-drivenbeanareequivalent,allowingtheEJBcontainertoassignamessagetoanymessage-drivenbeaninstance.Thecontainercanpooltheseinstancestoallowstreamsofmessagestobeprocessedconcurrently.
- Asinglemessage-drivenbeancanprocessmessagesfrommultipleclients.
Theinstancevariablesofthemessage-drivenbeaninstancecancontainsomestateacrossthehandlingofclientmessages--forexample,aJMSAPIconnection,anopendatabaseconnection,oranobjectreferencetoanenterprisebeanobject.Whenamessagearrives,thecontainercallsthemessage-drivenbeansonMessagemethodtoprocessthemessage.TheonMessagemethodnormallycaststhemessagetooneofthefiveJMSmessagetypesandhandlesitinaccordancewiththeapplicationsbusinesslogic.TheonMessagemethodmaycallhelpermethods,oritmayinvokeasessionorentitybeantoprocesstheinformationinthemessageortostoreitinadatabase.Amessagemaybedeliveredtoamessage-drivenbeanwithinatransactioncontext,sothatalloperationswithintheonMessagemethodarepartofasingletransaction.Ifmessageprocessingisrolledback,themessagewillberedelivered.Formoreinformation,seeChapter7.WhentoUseMessage-DrivenBeans
SessionbeansandentitybeansallowyoutosendJMSmessagesandtoreceivethemsynchronously,butnotasynchronously.Toavoidtyingupserverresources,youmayprefernottouseblockingsynchronousreceivesinaserver-sidecomponent.Toreceivemessagesasynchronously,useamessage-drivenbean.TheContentsofanEnterpriseBean
Todevelopanenterprisebean,youmustprovidethefollowingfiles:
- Deploymentdescriptor:AnXMLfilethatspecifiesinformationaboutthebeansuchasitspersistencetypeandtransactionattributes.ThedeploytoolutilitycreatesthedeploymentdescriptorwhenyoustepthroughtheNewEnterpriseBeanwizard.
- Enterprisebeanclass:Implementsthemethodsdefinedinthefollowinginterfaces.
- Interfaces:Theremoteandhomeinterfacesarerequiredforremoteaccess.Forlocalaccess,thelocalandlocalhomeinterfacesarerequired.SeethesectionDefiningClientAccesswithInterfaces.(Pleasenotethattheseinterfacesarenotusedbymessage-drivenbeans.)
- Helperclasses:Otherclassesneededbytheenterprisebeanclass,suchasexceptionandutilityclasses.
YoupackagethefilesintheprecedinglistintoanEJBJARfile,themodulethatstorestheenterprisebean.AnEJBJARfileisportableandmaybeusedfordifferentapplications.ToassembleaJ2EEapplication,youpackageoneormoremodules--suchasEJBJARfiles--intoanEARfile,thearchivefilethatholdstheapplication.WhenyoudeploytheEARfilethatcontainsthebeansEJBJARfile,youalsodeploytheenterprisebeanontotheJ2EEserver.NamingConventionsforEnterpriseBeans
Becauseenterprisebeansarecomposedofmultipleparts,itsusefultofollowanamingconventionforyourapplications.Table3-2summarizestheconventionsfortheexamplebeansofthistutorial.<P><P><Palign=center>Table3-2NamingConventionsforEnterpriseBeans<Palign=center>Item<Palign=center>Syntax<Palign=center>Example<Palign=left>Enterprisebeanname(DD)<Palign=left><name>EJB<Palign=left>AccountEJB<Palign=left>EJBJARdisplayname(DD)<Palign=left><name>JAR<Palign=left>AccountJAR<Palign=left>Enterprisebeanclass<Palign=left><name>Bean<Palign=left>AccountBean<Palign=left>Homeinterface<Palign=left><name>Home<Palign=left>AccountHome<Palign=left>Remoteinterface<Palign=left><name><Palign=left>Account<Palign=left>Localhomeinterface<Palign=left>Local<name>Home<Palign=left>LocalAccountHome<Palign=left>Localinterface<Palign=left>Local<name><Palign=left>LocalAccount<Palign=left>Abstractschema(DD)<Palign=left><name><Palign=left>AccountDDmeansthattheitemisanelementinthebeansdeploymentdescriptor.<P>Aboutthisdocument
ThisdocumentisbuiltfromtheHTMLdocumentationsavailableatjava.sun.com.Itisregularlyupdated,whennewversionsoforiginaldocumentationsbecomeavailable.TodownloadupdatesandmanyotherWinHelpandHTMLHelpJavadocumentationsforfree,visitFranckAllimantswebsite:http://www.confluent.fr/javadoc/indexe.html(inEnglish)http://www.confluent.fr/javadoc(inFrench)
没有那个大公司会傻了吧唧用.net开发大型项目,开发了,那等于自己一半的生命线被微软握着呢。而.net不行,限制在window系统,又是捆绑,鄙视微软之! |
|