Hibernate 简化继承映射 外文翻译.docx
- 文档编号:3919347
- 上传时间:2022-11-26
- 格式:DOCX
- 页数:15
- 大小:169.41KB
Hibernate 简化继承映射 外文翻译.docx
《Hibernate 简化继承映射 外文翻译.docx》由会员分享,可在线阅读,更多相关《Hibernate 简化继承映射 外文翻译.docx(15页珍藏版)》请在冰豆网上搜索。
Hibernate简化继承映射外文翻译
Hibernatesimplifiesinheritancemapping
Hibernateisanobject-relationalmappingandpersistenceframeworkthatprovidesalotofadvancedfeatures,rangingfromintrospectiontopolymorphismandinheritancemapping.Butmappingclasshierarchiestoarelationaldatabasemodelmightprovesomewhatdifficult.Thisarticlecoversthreestrategiesthatyoucanuseinyoureverydayprogrammingtoeasilymapcomplexobjectmodelstorelationaldatabasemodels.
Overview
HibernateisapureJavaobject-relationalmappingandpersistenceframeworkthatallowsyoutomapplainoldJavaobjectstorelationaldatabasetablesusingXMLconfigurationfiles.UsingHibernatecansavealotofdevelopmenttimeonaproject,sincethewholeJDBClayerismanagedbytheframework.Thismeansthatyourapplication'sdataaccesslayerwillsitaboveHibernateandbecompletelyabstractedawayfromoftheunderlyingdatamodel.
Hibernatehasanumberofadvantagesoverothersimilarobject-relationalmappingapproaches(JDO,entitybeans,in-housedevelopment,andsoon):
it'sfreeandopensource,ithasachievedagoodlevelofmaturity,it'swidelyused,andithasaveryactivecommunityforum.
TointegrateHibernateintoanexistingJavaproject,you'llneedtowalkthroughthefollowingsteps:
1.DownloadthelatestreleaseoftheHibernateframeworkfromtheHibernateWebsite.CopythenecessaryHibernatelibraries(JARfiles)toyourapplication'sCLASSPATH.
2.CreatetheXMLconfigurationfilesthatwillbeusedtomapyourJavaobjectstoyourdatabasetables.(We'lldescribethatprocessinthisarticle.)
3.CopytheXMLconfigurationfilestoyourapplication'sCLASSPATH.
You'llnoticethatyoudon'thavetomodifyanyJavaobjectstosupporttheframework.Imagine,forinstance,thatyouneededtosomehowchangeadatabasetablethatyourJavaapplicationused--byrenamingacolumn,forexample.Onceyou'dchangedthetable,allyou'dhavetodotoupdateyourJavaapplicationwouldbetoupdatetheappropriateXMLconfigurationfile.Youwouldn'tneedtorecompileanyJavacode.
HibernateQueryLanguage(HQL)
HibernateprovidesaquerylanguagecalledHibernateQueryLanguage(HQL),whichisquitesimilarSQL.Forthoseofyouwhoprefergoodold-fashionedSQLqueries,Hibernatestillgivesyoutheopportunitytousethem.ButoursupportingexamplewilluseHQLexclusively.
HQLisquitesimpletouse.YouwillfindallthefamiliarkeywordsyouknowfromSQL,likeSELECT,FROM,andWHERE.HQLdiffersfromSQLinthatyoudon'twritequeriesdirectlyonyourdatamodel(thatis,onyourtables,columns,etc.),butratheronyouJavaobjects,usingtheirpropertiesandrelationships.
Listing1illustratesabasicexample.ThisHQLcoderetrievesallIndividualswhosefirstNameis"John."
Listing1.BasicHQLQuery
SELECT*FROMeg.hibernate.mapping.dataobject.IndividualWHEREfirstName="John"
YoucanrefertotheHQLreferencematerialontheHibernateWebsiteifyouwanttolearnmoreaboutHQLsyntax.
XMLconfigurationfiles
ThecoreofHibernate'sfunctionalityresidesinsideXMLconfigurationfiles.Thesefilesmustresideinyourapplication'sCLASSPATH.Weplacedthemintheconfigdirectoryofoursamplecodepackage
Thefirstfilethatwe'llexamineishibernate.cfg.xml.Itcontainsinformationregardingyourdatasource(DBURL,schemaname,username,password,etc.)andreferencestootherconfigurationfilesthatwillcontainyourmappinginformation.
TheremainingXMLfilesallowyoutomapJavaclassesagainstdatabasetables.Wewilltakeacloserlookatthosefileslater,butitisimportanttoknowthattheirfilenamesfollowthepatternClassName.hbm.xml.
Oursupportingexample
Inthisarticle,we'llexamineabasicexamplethatillustrateshowHibernateworksandputstogoodusethreedifferentstrategiesunderwhichyoucanuseHibernatetodoyourobject-relationalmapping.Ourexampleapplicationwillbeusedbyaninsurancecompanythatmustkeeplegalrecordsofallthepropertyrightsthatitscustomersareinsuredfor.We'veprovidedthefullsourcecodewiththisarticle;thiscodeprovidesbasicfunctionalityfromwhichyoucouldbuildafull-fledgedapplication,suchasaWeborSwingapplication.
Ourexampleassumesaclassicusecaseforthiskindofapplication.Theuserwouldprovidethesearchcriteriaforanytypeofcustomer(individual,corporation,governmentagency,etc.),andwouldthenbepresentedwithalistofallcustomersmatchingthespecifiedcriteria--evenifthesearedifferenttypesofcustomers.Theusercouldaccessamoredetailedviewofaspecificcustomerfromthatsamelist.
Inourapplication,apropertyrightisrepresentedbytheRightclass.ARightcaneitherbeaLeaseoraProperty.ARightisownedbyacustomer.Torepresentourcustomer,we'llusethegenericclassPerson.APersoncaneitherbeanIndividualoraCorporation.Ofcourse,theinsurancecompanymustknowtheEstatestowhichthoseRightsareassigned.AnEstateisaverygenericterm,you'llagree.So,we'llusetheLandandBuildingclassestogiveourdevelopersmorecomprehensiveobjectstoworkwith.
Fromthisabstract,wecandeveloptheclassmodelshowninFigure1:
Figure1.CompleteClassModel
Ourdatabasemodelwasdesignedtocoverthethreedifferentstrategieswe'lldiscussinthisarticle.FortheRighthierarchy,we'lluseasingletable(TB_RIGHT)andmaptothecorrectclassusingtheDISCRIMINATORcolumn.ForthePersonhierarchy,we'llusewhatwecallasupertable(TB_PERSON)thatwillsharethesameIDswithtwoothertables(TB_CORPORATIONandTB_INDIVIDUAL).Thethirdhierarchy(Estate)usestwodifferenttables(TB_BUILDINGandTB_LAND)linkedbyaforeignkeydefinedbythecombinationoftwocolumns(REF_ESTATE_IDandREF_ESTATE_TYPE).
Figure2.Completedatamodel
Settingupthedatabase
HibernatesupportsawidevarietyofRDBMSs,andanyofthemshouldworkwithoursample.However,thesamplecodeandthetextofthisarticlehavebeentailoredforHSQLDB,afullyfunctionalrelationaldatabasewrittenentirelyintheJavalanguage.Inthesqldirectoryofthesamplecodepackage,youwillfindafilenameddatamodel.sql.ThisSQLscriptwillcreatethedatamodelusedinourexample.
SettinguptheJavaproject
Althoughyoucanalwaysbuildandexecutethesamplecodeusingthecommandline,youmaywanttoconsidersettinguptheprojectinanIDEforbetterintegration.Withinthesamplecodepackage,you'llfindthefollowingdirectories:
∙config,whichcontainsallthesample'sXMLconfigurationfiles(mapping,Log4J,etc.)
∙data,whichcontainsconfigurationfilesusedbyHSQLDB.YouwillalsofindabatchfilenamedstartHSQLDB.batthatyoumayusetolaunchthedatabase.
∙src,containsallthesample'ssourcecode.
BesuretocopytherequiredJavalibrariesandXMLconfigurationfilestoyouapplication'sCLASSPATH.ThecodeneedsonlytheHibernateandHSQLDBlibrariesinordertocompileandrunproperly.
Strategy1:
Onetablepersubclass(Persons)
Inourfirststrategy,we'lllookathowtomapourPersonhierarchy.You'llnoticethatthedatamodelisveryclosetoourclassmodel.Asaresult,we'lluseadifferenttableforeachclassinthehierarchy,butallthesetablesmustsharethesameprimarykey(we'llexplainthatinmoredetailmomentarily).Hibernatewillthenusethisprimarykeywhenitinsertsnewrecordsintothedatabase.ItwillalsomakeuseofthissameprimarykeytoperformJOINoperationswhenaccessingthedatabase.
Nowweneedtomapourobjecthierarchytoourtablemodel.Wehavethreetables(TB_PERSON,TB_INDIVIDUAL,andTB_CORPORATION).Aswementionedabove,theyallhaveacolumnnamedIDasaprimarykey.It'snotmandatorytohaveasharedcolumnnamelikethis,butitisconsideredgoodpractice--anditmakesitaloteasiertoreadthegeneratedSQLqueries.
IntheXMLmappingfile,showninListing2,you'llnoticethatthetwoconcreteclassesaredeclaredas
Listing2.Person.hbm.xml
xmlversion="1.0"encoding="UTF-8"?
>
DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD2.0//EN"
"
SavinganewinstanceofIndividualformourJavacodewithHibernateisprettystraightforward,asshowninListing3:
Listing3.SavinganewinstanceofIndividual
publicObjectcreate(Objectobject){
Sessionsession=null;
try{
session=sessionFactory.openSession();
Transactiontx=session.beginTransaction();
session.save(object);
session.fl
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Hibernate 简化继承映射 外文翻译 简化 继承 映射 外文 翻译
![提示](https://static.bdocx.com/images/bang_tan.gif)