HibernateData Access with the Spring Framework.docx
- 文档编号:2369394
- 上传时间:2023-05-03
- 格式:DOCX
- 页数:21
- 大小:22.54KB
HibernateData Access with the Spring Framework.docx
《HibernateData Access with the Spring Framework.docx》由会员分享,可在线阅读,更多相关《HibernateData Access with the Spring Framework.docx(21页珍藏版)》请在冰点文库上搜索。
HibernateDataAccesswiththeSpringFramework
DataAccesswiththeSpringFramework
(featuringHibernateexamples)
JuergenHoeller
July2003
0.Preface:
SpringBenefitsforHibernateUsers
Spring'slightweightbeancontaineroffersIoC-stylewiringupofbusinessobjects,DAOs,andresourceslikeJDBCDataSourcesandHibernateSessionFactories.SuchanXML-definedapplicationcontextisapowerfulalternativetomanuallymanagedsingletonsorfactoriesthatparsetheirconfigurationfromcustompropertiesfiles.Asnon-intrusivenessisacentralgoal,suchSpring-configuredapplicationbeansdonotneedtodependonSpringinterfacesorclassesbutgetconfiguredviatheirbeanproperties.Thisconceptcanbeappliedinanyenvironment,beitaJ2EEwebapp,adesktopapp,orevenanapplet.
InthecontextofHibernate,Spring'sgenerictransactionmanagementforDAOsisofparticularinterest.Thegoalistoseparatedataaccessandtransactiondemarcationaspectstoallowforreusabletransactionalbusinessobjectsthatarenottiedtoanyspecificdataaccessortransactionstrategy.DemarcationcaneitherhappenprogrammaticallyviaTransactionTemplate,ordeclarativelyviatheAOPTransactionInterceptor.BothnativeHibernate/JDBCtransactionsandJTAaresupportedasstrategiesout-of-the-box.ThisisaviablealternativetolocalStatelessSessionBeans.
Spring'sHibernateTemplateoffersasimplewaytoimplementHibernate-basedDAOswithoutcaringabouthandlingSessioninstancesorparticipatingintransactions.Noneedfortry-catchblocks,noneedfortransactionchecks.AsimpleHibernateaccessmethodcanbeaone-liner!
CombiningheterogeneousDAOsworksseamlessly,bothintermsofDAOinterfacesandparticipatingintransactions.Forexample,certainDAOscanbeimplementedonplainJDBC,preferablyviaSpring'sJdbcTemplatetoavoidmanualexceptionhandling.
YoucanusealotofSpring'sfeaturesrespectivelyclassesinalibrarystyle,aseverythingisdesignedasasetofreusableJavaBeans.Don'tbediscouragedbythefactthatSpringcanserveasfullapplicationframeworktoo!
Theapplicationcontextconceptisanadditionalbenefit,notarequirementforusingotherSpringfeatures.Inanycase,you'reinvitedtoreviewandleveragetheSpringapproach,nomattertowhatextent,beforedecidingtotaketheeffortandriskofbuildingsuchinfrastructurein-house.
1.Introduction:
ResourceManagement
Typicalbusinessapplicationsareoftenclutteredwithrepetitiveresourcemanagementcode.Manyprojectstrytoinventownsolutionsforthisissue,sometimessacrificingproperhandlingoffailuresforprogrammingconvenience.Springadvocatesstrikinglysimplesolutionsforproperresourcehandling:
Inversionofcontrolviatemplating,i.e.infrastructureclasseswithcallbackinterfaces,orapplyingAOPinterceptors.Theinfrastructurecaresforproperresourcehandling,andforappropriateconversionofspecificAPIexceptionstoanuncheckedinfrastructureexceptionhierarchy.
SpringintroducesaDAOexceptionhierarchy,applicabletoanydataaccessstrategy.FordirectJDBC,theJdbcTemplateclasscaresforconnectionhandling,andforproperconversionofSQLExceptiontotheDataAccessExceptionhierarchy,includingtranslationofdatabase-specificSQLerrorcodestomeaningfulexceptionclasses.ItsupportsbothJTAandJDBCtransactions,viarespectiveSpringtransactionmanagers.SpringalsooffersHibernateandJDOsupport,consistingofaHibernateTemplate/JdoTemplateanalogoustoJdbcTemplate,aHibernateInterceptor/JdoInterceptor,andaHibernate/JDOtransactionmanager.
Themajorgoalistoallowforclearapplicationlayering,withanydataaccessandtransactiontechnology,andforloosecouplingofapplicationobjects.Nomorebusinessobjectdependenciesonthedataaccessortransactionstrategy,nomorehard-codedresourcelookups,nomorehard-to-replacesingletons,nomorecustomserviceregistries.Onesimpleandconsistentapproachtowiringupapplicationobjects,keepingthemasreusableandfreefromcontainerdependenciesaspossible.
AlltheindividualdataaccessfeaturesareusableontheirownbutintegratenicelywithSpring'sapplicationcontextconcept,providingXML-basedconfigurationandcross-referencingofplainJavaBeaninstancesthatdon'tneedtobeSpring-aware.InatypicalSpringapp,manyimportantobjectsareJavaBeans:
dataaccesstemplates,dataaccessobjects(thatusethetemplates),transactionmanagers,businessobjects(thatusethedataaccessobjectsandtransactionmanagers),webviewresolvers,webcontrollers(thatusethebusinessobjects),etc.
2.ResourceDefinitionsinanApplicationContext
Toavoidtyingapplicationobjectstohard-codedresourcelookups,SpringallowstodefineresourceslikeaJDBCDataSourceoraHibernateSessionFactoryasbeansinanapplicationcontext.Applicationobjectsthatneedtoaccessresourcesjustreceivereferencestosuchpre-definedinstancesviabeanreferences(theDAOdefinitioninthenextsectionillustratesthis).ThefollowingexcerptfromanXMLapplicationcontextdefinitionshowshowtosetupaJDBCDataSourceandaHibernateSessionFactoryontopofit:
...
NotethatswitchingfromaJNDI-locatedDataSourcetoalocallydefinedonelikeaJakartaCommonsDBCPBasicDataSourceisjustamatterofconfiguration:
hsqldb:
hsql:
//localhost:
9001
YoucanalsouseaJNDI-locatedSessionFactory,butthat'stypicallynotnecessaryoutsideanEJBcontext(seethe"containerresourcesvslocalresources"sectionforadiscussion).
3.InversionofControl:
TemplateandCallback
Thebasicprogrammingmodelfortemplatinglooksasfollows,formethodsthatcanbepartofanycustomdataaccessobjectorbusinessobject.Therearenorestrictionsontheimplementationofthesurroundingobjectatall,itjustneedstoprovideaHibernateSessionFactory.Itcangetthelatterfromanywhere,butpreferablyasbeanreferencefromaSpringapplicationcontext-viaasimplesetSessionFactorybeanpropertysetter.ThefollowingsnippetsshowaDAOdefinitioninaSpringapplicationcontext,referencingtheabovedefinedSessionFactory,andanexampleforaDAOmethodimplementation.
...
publicclassProductDaoImplimplementsProductDao{
privateSessionFactorysessionFactory;
publicvoidsetSessionFactory(SessionFactorysessionFactory){
this.sessionFactory=sessionFactory;
}
publicListloadProductsByCategory(finalStringcategory){
HibernateTemplatehibernateTemplate=newHibernateTemplate(this.sessionFactory);
return(List)hibernateTemplate.execute(
newHibernateCallback(){
publicObjectdoInHibernate(Sessionsession)throwsHibernateException{
Listresult=session.find("fromtest.Productproductwhereproduct.category=?
",category,Hibernate.STRING);
//dosomefurtherstuffwiththeresultlist
returnresult;
}
});
}
}
AcallbackimplementationcaneffectivelybeusedforanyHibernatedataaccess.HibernateTemplatewillcareforproperSessionopeningandclosinginanycase,andforautomaticallyparticipatingintransactions.Thetemplateinstancesarethread-safeandreusable,theycanthusbekeptasinstancevariablesofthesurroundingclass.
Forsimplesinglestepactionslikeasinglefind,load,saveOrUpdate,ordeletecall,HibernateTemplateoffersalternativeconveniencemethodsthatcanreplacesuchonelinecallbackimplementations.Furthermore,SpringprovidesaconvenientHibernateDaoSupportbaseclassthatprovidesasetSessionFactorymethodforreceivingaSessionFactory,andgetSessionFactoryandgetHibernateTemplateforusebysubclasses.Incombination,thisallowsforverysimpleDAOimplementationsfortypicalrequirements:
publicclassProductDaoImplextendsHibernateDaoSupportimplementsProductDao{
publicListloadProductsByCategory(Stringcategory){
returngetHibernateTemplate().find("fromtest.Productproductwhereproduct.category=?
",category);
}
}
4.ApplyinganAOPInterceptorInsteadofaTemplate
AnalternativetousingaHibernateTemplateisSpring'sAOPHibernateInterceptor,replacingthecallbackimplementationwithstraightHibernatecodewithinadelegatingtry/catchblock,andarespectiveinterceptorconfigurationintheapplicationcontext.ThefollowingsnippetsshowrespectiveDAO,interceptor,andproxydefinitionsinaSpringapplicationcontext,andanexampleforaDAOmethodimplementation.
...
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Hibernate Data Access with the Spring Framework
链接地址:https://www.bingdoc.com/p-2369394.html