Hibernate 简化继承映射 外文翻译Word文档格式.docx

上传人:b****6 文档编号:16825535 上传时间:2022-11-26 格式:DOCX 页数:15 大小:169.41KB
下载 相关 举报
Hibernate 简化继承映射 外文翻译Word文档格式.docx_第1页
第1页 / 共15页
Hibernate 简化继承映射 外文翻译Word文档格式.docx_第2页
第2页 / 共15页
Hibernate 简化继承映射 外文翻译Word文档格式.docx_第3页
第3页 / 共15页
Hibernate 简化继承映射 外文翻译Word文档格式.docx_第4页
第4页 / 共15页
Hibernate 简化继承映射 外文翻译Word文档格式.docx_第5页
第5页 / 共15页
点击查看更多>>
下载资源
资源描述

Hibernate 简化继承映射 外文翻译Word文档格式.docx

《Hibernate 简化继承映射 外文翻译Word文档格式.docx》由会员分享,可在线阅读,更多相关《Hibernate 简化继承映射 外文翻译Word文档格式.docx(15页珍藏版)》请在冰豆网上搜索。

Hibernate 简化继承映射 外文翻译Word文档格式.docx

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

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

当前位置:首页 > 考试认证 > 财会金融考试

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1