HibernateData Access with the Spring Framework文档格式.docx
《HibernateData Access with the Spring Framework文档格式.docx》由会员分享,可在线阅读,更多相关《HibernateData Access with the Spring Framework文档格式.docx(21页珍藏版)》请在冰点文库上搜索。
![HibernateData Access with the Spring Framework文档格式.docx](https://file1.bingdoc.com/fileroot1/2023-5/3/4201cda1-4054-4f5d-9eeb-58e489e0c7f8/4201cda1-4054-4f5d-9eeb-58e489e0c7f81.gif)
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:
<
beanid="
myDataSource"
class="
org.springframework.jndi.JndiObjectFactoryBean"
>
<
propertyname="
jndiName"
value>
jdbc/myds<
/value>
/property>
/bean>
mySessionFactory"
org.springframework.orm.hibernate.LocalSessionFactoryBean"
mappingResources"
list>
product.hbm.xml<
/list>
hibernateProperties"
props>
propkey="
hibernate.dialect"
net.sf.hibernate.dialect.MySQLDialect<
/prop>
/props>
dataSource"
refbean="
/>
...
NotethatswitchingfromaJNDI-locatedDataSourcetoalocallydefinedonelikeaJakartaCommonsDBCPBasicDataSourceisjustamatterofconfiguration:
mons.dbcp.BasicDataSource"
destroy-method="
close"
driverClassName"
org.hsqldb.jdbcDriver<
url"
jdbc:
hsqldb:
hsql:
//localhost:
9001<
username"
sa<
password"
YoucanalsouseaJNDI-locatedSessionFactory,butthat'
stypicallynotnecessaryoutsideanEJBcontext(seethe"
containerresourcesvslocalresources"
sectionforadiscussion).
3.InversionofControl:
TemplateandCallback
Thebasicprogrammingmodelfortemplatinglooksasfollows,formethodsthatcanbepartofanycustomdataaccessobjectorbusinessobject.Therearenorestrictionsontheimplementationofthesurroundingobjectatall,itjustneedstoprovideaHibernateSessionFactory.Itcangetthelatterfromanywhere,butpreferablyasbeanreferencefromaSpringapplicationcontext-viaasimplesetSessionFactorybeanpropertysetter.ThefollowingsnippetsshowaDAOdefinitioninaSpringapplicationcontext,referencingtheabovedefinedSessionFactory,andanexampleforaDAOmethodimplementation.
myProductDao"
product.ProductDaoImpl"
sessionFactory"
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("
category);
4.ApplyinganAOPInterceptorInsteadofaTemplate
AnalternativetousingaHibernateTemplateisSpring'
sAOPHibernateInterceptor,replacingthecallbackimplementationwithstraightHibernatecodewithinadelegatingtry/catchblock,andarespectiveinterceptorconfigurationintheapplicationcontext.ThefollowingsnippetsshowrespectiveDAO,interceptor,andproxydefinitionsinaSpringapplicationcontext,andanexampleforaDAOmethodimplementation.
myHibernateInterceptor"
org.springframework.orm.hibernate.HibernateInterceptor"
myProductDaoTarget"
se