HibernateData Access with the Spring Framework文档格式.docx

上传人:b****1 文档编号:4446884 上传时间:2023-05-03 格式:DOCX 页数:21 大小:22.54KB
下载 相关 举报
HibernateData Access with the Spring Framework文档格式.docx_第1页
第1页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第2页
第2页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第3页
第3页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第4页
第4页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第5页
第5页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第6页
第6页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第7页
第7页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第8页
第8页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第9页
第9页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第10页
第10页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第11页
第11页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第12页
第12页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第13页
第13页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第14页
第14页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第15页
第15页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第16页
第16页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第17页
第17页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第18页
第18页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第19页
第19页 / 共21页
HibernateData Access with the Spring Framework文档格式.docx_第20页
第20页 / 共21页
亲,该文档总共21页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

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

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

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

当前位置:首页 > 求职职场 > 简历

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2