Hibernate 简化继承映射 外文翻译Word文档格式.docx
- 文档编号:16825535
- 上传时间:2022-11-26
- 格式:DOCX
- 页数:15
- 大小:169.41KB
Hibernate 简化继承映射 外文翻译Word文档格式.docx
《Hibernate 简化继承映射 外文翻译Word文档格式.docx》由会员分享,可在线阅读,更多相关《Hibernate 简化继承映射 外文翻译Word文档格式.docx(15页珍藏版)》请在冰豆网上搜索。
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<
joined-subclass>
insidethePersonmappingdefinition.TheXMLelement<
id>
ismappedtotheprimarykeyforthetop-leveltableTB_PERSON,whilethe<
key>
elements(fromeachsubclass)aremappedtothematchingprimarykeysoftheTB_INDIVIDUALandTB_CORPORATIONtables.
Listing2.Person.hbm.xml
<
?
xmlversion="
1.0"
encoding="
UTF-8"
>
!
DOCTYPEhibernate-mappingPUBLIC"
-//Hibernate/HibernateMappingDTD2.0//EN"
"
hibernate-mapping>
<
classname="
eg.hibernate.mapping.dataobject.Person"
table="
TB_PERSON"
polymorphism="
implicit"
idname="
id"
column="
ID"
generatorclass="
assigned"
/>
/id>
setname="
rights"
lazy="
false"
keycolumn="
REF_PERSON_ID"
one-to-manyclass="
eg.hibernate.mapping.dataobject.Right"
/>
/set>
joined-subclassname="
eg.hibernate.mapping.dataobject.Individual"
TB_INDIVIDUAL"
propertyname="
firstName"
FIRST_NAME"
type="
java.lang.String"
lastName"
LAST_NAME"
/joined-subclass>
eg.hibernate.mapping.dataobject.Corporation"
TB_CORPORATION"
name"
NAME"
string"
registrationNumber"
REGISTRATION_NUMBER"
/class>
/hibernate-mapping>
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 简化继承映射 外文翻译 简化 继承 映射 外文 翻译