Tải bản đầy đủ (.pdf) (696 trang)

OReilly harnessing hibernate apr 2008 ISBN 0596517726

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.72 MB, 696 trang )

HarnessingHibernate
byJamesElliott;TimothyM.O'Brien;RyanFowler
Publisher:O'Reilly
PubDate:April28,2008
PrintISBN-13:978-0-596-51772-4
Pages:380
TableofContents|Index

Overview
HarnessingHibernateisanidealintroductiontothepopular
frameworkthatletsJavadevelopersworkwithinformationfrom
arelationaldatabaseeasilyandefficiently.Databasesareavery
differentworldthanJavaobjects,andtheyofteninvolvepeople
withdifferentskillsandspecializations.WithHibernate,bridging
thesetwoworldsissignificantlyeasier,andwiththisbook,you
cangetuptospeedwithHibernatequickly.Ratherthanpresent
youwithanotherreference,HarnessingHibernateletsyou
explorethesystem,fromdownloadandconfigurationthrougha
seriesofprojectsthatdemonstratehowtoaccomplishavariety
ofpracticalgoals.Theneweditionofthisconciseguidewalks
youthroughHibernate'sprimaryfeatures,whichinclude
mappingfromJavaclassestodatabasetables,andfromJava
datatypestoSQLdatatypes.Youwillalsolearnabout
Hibernate'sdataqueryandretrievalfacilities,andmuchmore.
Byreadingandfollowingalongwiththeexamples,youcanget
yourownHibernateenvironmentsetupquicklyandstartusing
itforreal-worldtasksrightaway.HarnessingHibernateteaches
youhowto:
PerformObject/Relationalmapping
WorkwithpersistentdatafromJavacode
Workwithgroupsandrelationshipsbetweenobjects




ExtendHibernate'srichtypesupportforyourownneeds
Simplifyquerycreationusingcriteriaandexamples
UsetheHibernateQueryLanguage(HQL)andunderstand
howitdiffersfromSQL
UseHibernateinconjunctionwithSpring
UseHibernateinconjunctionwithotherpackages,suchas
theStripeswebframeworkandtheEclipseIDE
Onceyou'repastthefirstfewchapters,youcanjumptotopics
thatyoufindparticularlyinterestingorrelevant.Allbackground
materialandexplanationsofhowHibernateworksandwhyisin
theserviceofafocusedtask.Sourcecodecanbedownloaded
fromthebook'swebsite.IfusingSQLisanuncomfortable
chore,HarnessingHibernateoffersyouaneffectiveandtroublefreemethodforworkingwiththeinformationyoustoreinyour
applications.


HarnessingHibernate
byJamesElliott;TimothyM.O'Brien;RyanFowler
Publisher:O'Reilly
PubDate:April28,2008
PrintISBN-13:978-0-596-51772-4
Pages:380
TableofContents|Index

Copyright
Preface
Part1:HibernateinaHurry
Chapter1.InstallationandSetup

Section1.1.GettinganAntDistribution
Section1.2.CheckYourJavaVersion
Section1.3.GettingtheMavenTasksforAnt
Section1.4.InstallingtheMavenTasksforAnt
Section1.5.UsingtheHSQLDBDatabaseEngine
Section1.6.UsingHibernateCore
Section1.7.SettingUpaProjectHierarchy
Chapter2.IntroductiontoMapping
Section2.1.WritingaMappingDocument
Section2.2.GeneratingSomeClass
Section2.3.CookingUpaSchema
Chapter3.HarnessingHibernate
Section3.1.ConfiguringHibernate
Section3.2.CreatingPersistentObjects
Section3.3.FindingPersistentObjects
Section3.4.BetterWaystoBuildQueries
Chapter4.CollectionsandAssociations
Section4.1.MappingCollections
Section4.2.PersistingCollections


Section4.3.RetrievingCollections
Section4.4.UsingBidirectionalAssociations
Section4.5.WorkingwithSimplerCollections
Chapter5.RicherAssociations
Section5.1.EagerandLazyAssociations
Section5.2.OrderedCollections
Section5.3.AugmentingAssociationsinCollections
Section5.4.LifecycleAssociations
Section5.5.ReflexiveAssociations

Chapter6.CustomValueTypes
Section6.1.DefiningaUserType
Section6.2.DefiningaPersistentEnumeratedType
Section6.3.UsingaCustomTypeMapping
Section6.4.WorkingwithPersistentEnumerations
Section6.5.BuildingaCompositeUserType
Chapter7.TheAnnotationsAlternative
Section7.1.HibernateAnnotations
Section7.2.AnnotatingModelObjects
Section7.3.AnAlternateApproach
Chapter8.CriteriaQueries
Section8.1.UsingSimpleCriteria
Section8.2.CompoundingCriteria
Section8.3.ProjectionandAggregationwithCriteria
Section8.4.ApplyingCriteriatoAssociations
Section8.5.QueryingbyExample
Section8.6.Property-OrientedCriteriaFactories
Chapter9.ALookatHQL
Section9.1.WritingHQLQueries
Section9.2.SelectingPropertiesandPieces
Section9.3.Sorting
Section9.4.WorkingwithAggregateValues
Section9.5.WritingNativeSQLQueries


Part2:PlayingNicewithOthers
Chapter10.ConnectingHibernatetoMySQL
Section10.1.SettingUpaMySQLDatabase
Section10.2.ConnectingtoMySQL
Section10.3.TryingItOut

Section10.4.LookingattheData
Chapter11.HibernateandEclipse:ReallyUsingthe
HibernateTools
Section11.1.InstallingtheHibernateToolsinEclipse
Section11.2.CreatingaHibernateConsoleConfiguration
Section11.3.MoreEditingSupport
Section11.4.TheHibernateConsolePerspective
Section11.5.CodeGeneration
Section11.6.MappingDiagrams
Chapter12.MaveninMoreDepth
Section12.1.WhatIsMaven?
Section12.2.InstallingMaven
Section12.3.Building,Testing,andRunningaProject
Section12.4.GeneratingIDEProjectFilesusingMaven
Section12.5.GeneratingReportswithMaven
Section12.6.AMavenProjectObjectModel
Section12.7.TheMavenBuildLifecycle
Section12.8.UsingtheMavenHibernate3Plug-in
Section12.9.BecomingaMavenMaven
Chapter13.PutaSpringinyourStep:Hibernatewith
Spring
Section13.1.WhatIsSpring?
Section13.2.WritingaDataAccessObject
Section13.3.CreatinganApplicationContext
Section13.4.PuttingItAllTogether
Chapter14.TheFinishingTouch:StripeswithSpringand
Hibernate


Section14.1.EarnYourStripes

Section14.2.PrepareTomcat
Section14.3.CreatetheWebApplication
Section14.4.AddStripes
Section14.5.DealingwithAssociations
AppendixA.HibernateTypes
SectionA.1.BasicTypes
SectionA.2.CustomValueTypes
SectionA.3."Any"TypeMappings
SectionA.4.AllTypes
AppendixB.TheCriteriaAPI
SectionB.1.TheCriterionFactory
SectionB.2.TheProjectionFactory
SectionB.3.TheOrderFactory
SectionB.4.ThePropertyFactory
AppendixC.HibernateSQLDialects
SectionC.1.GettingFluentintheLocalSQL
AppendixD.SpringTransactionSupport
SectionD.1.UsingtheSpringFramework'sTransactional
Annotation
SectionD.2.UsingaJTATransactionManager
AppendixE.WheretoGoNext
SectionE.1.OnlineManuals
SectionE.2.Books
SectionE.3.SourceCode
SectionE.4.DealingwithNewerReleases
SectionE.5.GettingInvolved
Colophon
Index



Copyright
Copyright©2008,JamesElliott,RyanFowler,andTimO'Brien.
Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformation,
contactourcorporate/institutionalsalesdepartment:800-9989938or
Editor:MikeLoukides
ProductionEditor:SarahSchneider
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
HarnessingHibernate,theimageofahedgehog,andrelated
tradedressaretrademarksofO'ReillyMedia,Inc.
Manyofthedesignationsusesbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.


Preface
Hibernateisalightweightobject/relationalmappingservicefor
Java.Whatdoesthatmean?It'sawaytoworkeasilyand

efficientlywithinformationfromarelationaldatabaseinthe
formofnaturalJavaobjects.Butthatdescriptiondoesn'tcome
closetoconveyinghowusefulandexcitingthetechnologyis.
I'mnottheonlypersonwhothinksso:Hibernate2.1won
SoftwareDevelopmentmagazine's14thannualJoltAwardin
the"Libraries,Frameworks,andComponents"category.(And,
withthehindsightaffordedbytheopportunitytowritethis
updatedandexpandedversionofHibernate:ADeveloper's
Notebook,IcansayIwastrulythrilledthatthefirsteditionof
thisbook,whichcoveredHibernate2,wasitselfaProductivity
Winnerinthe15thannualAwards.)
So,what'sgreataboutHibernate?Allnontrivialapplications
(andevenmanytrivialones)needtostoreanduseinformation,
andthesedaysthisusuallyinvolvesarelationaldatabase.
WorldsapartfromJavaobjects,databasesofteninvolvepeople
withdifferentskillsandspecializations.Bridgingthesetwo
worldshasbeenimportantforawhile,butitusedtobequite
complexandtedious.
MostpeoplestartoutstrugglingtowriteafewSQLqueries,
embeddingtheseawkwardlyasstringswithinJavacode,and
workingwithJavadatabaseconnectivity(JDBC)torunthem
andprocesstheresults.JDBChasevolvedintoarichand
flexibledatabasecommunicationlibrary,whichnowprovides
waystosimplifyandimproveuponthisapproach,butthereis
stillafairdegreeoftediuminvolved.Peoplewhoworkwithdata
agreatdealneedmorepower—somewayofmovingthe
queriesoutofthecodeandmakingthemactmorelikewellbehavedcomponentsinanobject-orientedworld.
Suchcapabilitieshadbeenpartofmyown(evenmore)
lightweightobject/relationallayerforyears.Itbeganwitha
Javadatabaseconnectionandquerypoolingsystemwrittenby



mycolleagueEricKnappfortheLands'Ende-commercesite.
OurpoolerintroducedtheideaofexternalSQLtemplatesthat
couldbeaccessedbynameandefficientlycombinedwith
runtimedatatogeneratetheactualdatabasequeries.Only
laterdiditgrowtoincludetheabilitytobindthesetemplates
directlytoJavaobjects,byaddingsimplemappingdirectivesto
thetemplates.
AlthoughfarlesspowerfulthanasystemlikeHibernate,this
approachprovedvaluableinmanyprojectsofdifferentsizes
andinwidelydifferingenvironments.Wecontinuedtouseit
untilthefirstversionofthisbook,mostrecentlyinbuildingIP
telephonyapplicationsforCisco'sCallManagerplatform.
However,wenowuseHibernatefornewprojects,andonceyou
workthroughthisbook,you'llunderstandwhy.Youwill
probablymakethesamedecisionyourself.Hibernatedoesa
tremendousamountforyou,anddoesitsoeasilythatyoucan
almostforgetyou'reworkingwithadatabase.Yourobjectsare
simplytherewhenyouneedthem.Thisishowtechnology
shouldwork.
YoumaywonderhowHibernaterelatestoEnterprise
JavaBeans™(EJBs).Isitacompetingsolution?Whenwould
youuseoneovertheother?Infact,youcanuseboth.Not
everyapplicationneedsthecomplexityofEJBs;manycan
simplyuseHibernatedirectlytointeractwithadatabase.On
theotherhand,EJBsaresometimesindispensableforvery
complexthree-tierapplicationenvironments.Insuchcases,
HibernatemaybeusedbyanEJBSessionbeantopersistdata,
oritmightbeusedtopersistBMPentitybeans.

Infact,eventheEJBcommitteewaseventuallysoldonthe
powerandconvenienceofHibernate's"plainoldJavaobjects"
approachtopersistence—theJavaPersistenceArchitecture
introducedinEJBversion3(andusableoutsideofanEJB
environment)washeavilyinfluencedbyHibernate.Infact,
Hibernate3canbeusedasanimplementationofJPAinafully
portableway(although,asyou'llseeinChapter7,you'll


probablystillwanttotakeadvantageofHibernate'sextensions
toJPA).
ThedevelopmentofHibernatehasclearlybeenawatershed
eventintheinteractionbetweenJavaandrelationaldatabases.
TheJavaworldowesGavinKingandhisintrepidcohortsahuge
debtofthanksformakingourliveseasier.Thisbookisintended
tohelpyoulearnhowtakeadvantageoftheirachievementas
quicklyaspossible.

P.1.HowtoUseThisBook
ThisbookstartedaspartofO'Reilly'sDeveloper'sNotebook™
series,anewapproachtohelpingreadersrapidlycomeupto
speedwithusefulnewtechnologies.Althoughithassincebeen
expandedtotouchonmoreoftherelatedtechnologiesthat
Hibernateusersmightwanttoexplore,itisnotintendedtobea
comprehensivereferencemanualforHibernate.Instead,it
reflectstheauthors'ownexplorationofthesystem,frominitial
downloadandconfigurationthroughaseriesofprojectsthat
demonstratehowtoaccomplishavarietyofpracticalgoals.
Byreadingandfollowingalongwiththeseexamples,you'llbe
abletogetyourownHibernateenvironmentsetupquicklyand

startusingitforrealistictasksrightaway.It'sasifyoucan
"walkwithus"throughterrainwe'vemappedout,whilewe
pointoutusefullandmarksandtrickypitfallsalongtheway.
Althoughwecertainlyincludesomebackgroundmaterialsand
explanationsofhowHibernateworksandwhy,thisisalwaysin
theserviceofafocusedtask.Sometimeswe'llreferyoutothe
referencedocumentationorotheronlineresourcesifyou'dlike
moredepthaboutoneoftheunderlyingconceptsordetails
aboutarelatedbutdifferentwaytouseHibernate.
Onceyou'repastthefirstfewchapters,youdon'tneedtoread
therestinorder;youcanjumptotopicsthatareparticularly
interestingorrelevanttoyou.Theexamplesdobuildoneach
other,butyoucandownloadthefinishedsourcecodefromthe


book'swebsite(youmaywanttostartwiththeprevious
chapter'sfilesandfollowalong,makingchangesyourselfto
implementtheexamplesyou'rereading).Youcanalwaysjump
backtotheearlierexamplesiftheyturnouttobeinteresting
becauseofhowtheyrelatetowhatyou'vejustlearned.

P.2.FontConventions
Thisbookfollowscertainconventionsforfontusage.
Understandingtheseconventionsupfrontwillmakeiteasierto
usethisbook.
Italic
Usedforfilenames,fileextensions,URLs,application
names,emphasis,andintroductionofnewterms.

Constantwidth

UsedforJavaclassnames,methods,variables,properties,
datatypes,databaseelements,andsnippetsofcodethat
appearintext.

Constantwidth
bold
Usedforcommandsyouenteratthecommandlineandto
highlightnewcodeinsertedinarunningexample.

Constantwidthitalic
Usedtoannotateoutput.

P.3.OntheWebSite


Thewebsiteforthisbook,
offerssome
importantmaterialsyou'llwanttoknowabout.Alltheexamples
forthisbookcanbefoundthere,organizedbychapter.
TheexamplesareavailableasaZIParchiveandacompressed
TARarchive.
Inmanycases,thesamefilesareusedthroughoutaseriesof
chapters,andtheyevolvetoincludenewfeaturesand
capabilitiesfromexampletoexample.Eachchapterfolderin
thedownloadablearchivecontainsasnapshotofthestateof
theexamplesystem,reflectingallthechangesandnewcontent
introducedinthatchapter.

P.4.HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbookto

thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)
O'Reilly'swebsiteforthisbook,wherewelisterrata,examples,
oranyadditionalinformation,canbeaccessedat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:




P.5.Acknowledgments
We'reintenselygratefultoGavinKing,ChristianBauer,Steve
Ebersole,MaxAndersen,andeveryoneelsewhohascreated
andimprovedHibernate.Ourenthusiasmforhowthistoolhas
madeourlivesbetterasJavadevelopersiswhyJimwrotethe
Developer'sNotebookinthefirstplace,andwhyallthreeofus
decidedtoproducethisexpandedandupdatedbook.Hopefully
itshows!
We'reparticularlyindebtedtoourtechnicalreviewersMichael
Podrazik,StefanWinz,andHenriYandellfortheircareful,
detailed,andhelpfulsuggestions.Theyeachcontributedgreatly
tomakingthisabetterbook.

We'dalsoliketothankKeithFahlgren,AdamWitwer,andthe
othermembersofO'Reilly'sproductiondepartmentwhoputin
lotsofworkhelpinguscomeuptospeedinthenewDocBook
XMLauthoringenvironment,andgettingthebooktolookas
goodasitcould.
TheStripesexampleincludescodedevelopedbyTimFennell,
undertheApacheSoftwareLicense.ThelicenseforStripesis
locatedatch14/stripes_license.txtintheexamplesdownload.

P.5.1.JamesElliott
Anylistofthankshastostartwithmyparentsforfosteringmy
interestincomputingevenwhenwewerelivingincountries
thatmadethatamajorchallenge,andwithmypartnerJoefor
puttingupwithittodaywhenithasfloweredintoamajor
obsession.I'dalsoliketoacknowledgemyemployer,Berbee,
forgivingmeanopportunitytodelvedeeplyintoJavaandbuild
skillsasanarchitectofreusableAPIs;forlettingmestayclear
oftheproprietary,platform-specifictarpitthatisengulfingso
muchoftheprogrammingworld;forsurroundingmewithsuch
incrediblecolleagues;andforbeingsupportivewhenIwanted


toleveragetheseexperiencesinwritingthisbook.
RyanandTimjumpedinwhenIwantedsomehelpexpanding
thesecondversiontocoverrelatedtechnologiesthathave
comeuplikeSpringandStripes.Theirenthusiasmand
expertisehavebeenamajorfactoringettingthislong-delayed
updateinmotion.
MarcLoygotmeconnectedwiththewonderfulfolksatO'Reilly
byinvitingmetohelpwiththesecondeditionofJavaSwing,

andMikeLoukideshasbeenpatientlyworkingwithmeever
since—encouragingmetowriteabookofmyown.InHibernate
hefoundtheperfecttopictogetmestarted,anditturnedout
wellenoughthatwecamebacktoexpandit.DebCameron,our
revisionseditorfortheSwingeffort,playedabigroleinturning
mytentativeauthorialambitionsintoarewardingreality.I'm
alsogratefulshewaswillingto"loanmeout"fromhelpingwith
thethirdeditionofLearningEmacstotakeontheHibernate
project.
Iremaingratefultomytechnicalreviewersforthefirstversion
ofthisbook,AdrianKellorandCurtPederson.Theylookedat
someveryearlydraftsandhelpedsetmytoneanddirection,as
wellasreinforcingmyenthusiasmaboutthevalueofthe
project.Asthatbookcametogether,BruceTateprovidedan
importantsanitycheckfromsomeoneactivelyusingand
teachingHibernate,andofferedsomegreatadviceandeven
moreencouragement.EricKnappreviewedalargeportionwith
aneyetowardusingthebookinaninstructionalsettingata
technicalcollege,andremindedmetokeepmyfeetonthe
ground.TimCartwrightjumpedinattheend,workingwitha
nearlycompletedraftinanefforttounderstandHibernateasa
potentialplatformforfuturework,andprovidingagreatdealof
usefulfeedbackaboutthecontentandpresentation.

P.5.2.RyanFowler
I'dliketothankJimforinvitingmetohelpoutonthisbookand
forallthecoachinghe'sgivenmeonthebookandinmyday


job.I'dliketothankTimforprovidingtechnicalhelpand

consolationwhenIneededeach.ThankstoMikeLoukidesfor
beingpatientwithmeandforhelpingtoprovidesomedirection.
I'dalsoliketothankmywife,Sarah,forbeingsohelpful,
patient,andloving.Thingscouldhaveturnedugly,andyour
supportwastheprimaryreasonthatdidn'thappen.Finally,I'd
liketothankmyparentsforgivingmethetoolstogetwhereI
amnowandwhereverI'mgoing.

P.5.3.TimothyO'Brien
ThankstoJimandRyanforaskingmetocontributetothisbook
withtheSpringandMavenchapters.ThankstoMikeLoukides
forprovidingagoodenvironmentforwritingandcollaboration.
KeithFahlgrenwasaninvaluableresourcewhenitcametothe
logisticsofwriting.TheO'Reillypublishingtechnologygroup
wentoutofitswayanumberoftimestohelpusallwith
variousissuesrelatingtoDocBookmarkupandversioncontrol.
ThankstoStefanWinz,RobertSorkin,AhmedAbu-Zayedeh,
BobHartlaub,RockPodrazik,andJeffLeeman;youhaveall
providedthenecessaryprovinggroundsandbeenunwitting
guineapigsforthecodepresentedinboththeSpringand
Mavenchapters.ThankstomydaughterJosephineAnnfor
providingessentialandcriticalfeedbackontheHibernate
Annotationschapter;Josephine,youmightonlybetwoyears
old,butyou'vepickedupHibernateveryquickly.Thanksfor
takingtimeofffromwatchingBlue'sCluestocatchthosesilly
errorsinmypom.xmlfile.ThankstoSusan,mywife,forbeing
perfect.


Part1:HibernateinaHurry

OurfirstgoalistogetuptospeedwithHibernateasquickly
aspossible.Mostofthechaptersinthispartareupdated
versionsofcontentfromHibernate:ADeveloper'sNotebook
(O'Reilly),reflectingthemajorchangesthatcameabout
withHibernate3.Thesamplecodenowworkswiththe
latestversionsofthetoolswerelyontoprovideaneasy
yetrealisticenvironmentforworkingwithHibernate.There
isalsoanewchaptercoveringtheabilitytouseJava5
annotations,ratherthanXMLmappingfiles,toconfigure
Hibernatemappings.

NOTE
Ofcourse,withanyprintedbookaboutactiveopen
sourceprojects,thingswillgetoutofdatequickly!
SeeAppendixEforthespecificversionswediscuss,
andforideasonhowtocopewithchanges.
Gettingstartedandfollowingalongwiththeexamplesis
eveneasierinthisnewversionofthebookbecausewe've
adoptedMaventohelpdownloadmanyofthetoolsand
libraries.Aswehopeyouwillsee,there'snoexcuseto
avoiddivinginandtryingthisstuffyourself!
Onceyou'recomfortablewiththefundamentalsof
Hibernate,Part2willdemonstratehowtotieHibernateinto
someotherenvironmentstomakeeachmorepowerfulthan
theyareontheirown.
Allright,timetodivein….


Chapter1.InstallationandSetup
Itcontinuestoamazemehowmanygreat,free,opensource

Java™toolsareoutthere.WhenIneededalightweight
object/relationalmappingserviceforaJSPe-commerceproject
attheturnofthemillennium,Ihadtobuildmyown.Itevolved
overtheyears,developedsomecoolanduniquefeatures,and
we'veuseditinawidevarietyofdifferentcontexts.But,onceI
discoveredHibernate,weusedthatfornewdevelopment
insteadofmyownfamiliarsystem(towardwhichI'llcheerfully
admitbias).Thatshouldtellyouhowcompellingitis!
Ifyou'relookingatthisbook,you'relikelyinterestedina
powerfulandconvenientwaytobridgetheworldsofJava
objectsandrelationaldatabases.Hibernatefillsthatrolevery
nicely,withoutbeingsocomplicatedthatlearningitbecomesa
dauntingchallengeinitself.Todemonstratethat,thischapter
guidesyoutothepointwhereyoucanplaywithHibernateand
seeforyourselfwhyit'ssoexciting.
LaterchapterswilllookatusingHibernateaspartofmore
complexenvironmentssuchasSpringandStripes,aswellas
usingitwithotherdatabases.Thegoalofthisfirstchapteristo
showyouhoweasyitistoputtogetherabasic,self-contained
environmentinwhichyoucanexploreHibernateanddoreal
thingswithit.

1.1.GettinganAntDistribution
Althoughitmightbesurprising,thefirstfewthingsyouneedto
getHibernaterunninghavenothingtodowithHibernateitself.
First,youmustsetupanenvironmentinwhichtheremaining
exampleswork.Thiswillhavethepleasantsideeffectof
buildingasolidfoundationforanyactualprojectyoumightbe
undertaking.
Ifyou'renotalreadyusingAnttomanagethebuilding,testing,

running,andpackagingofyourJavaprojects,nowisthetime


tostart.TheexamplesinthisbookareAnt-driven,soyou'll
needaworkingAntinstallationtorunthemandexperiment
withvariationsonyourownsystem,whichisthebestwayto
learn.
Firstofall,getanAntbinaryandinstallit.

1.1.1.WhydoIcare?
TheexamplesuseApacheAntforseveralreasons.It's
convenientandpowerful;it'soneofthestandardbuildtoolsfor
Java-baseddevelopment;it'sfree;andit'scross-platform.If
youuseAnt,theexampleswillworkequallywellanywhere
there'saJavaenvironment,whichmeansreadersofthisbook
won'tbefrustratedorannoyed.Fortunately,italsomeanswe
candomanymorecoolthingswithlesseffort—especiallysince
severalHibernatetoolshaveexplicitAntsupport,whichI'll
showyouhowtoleverage.(Ishouldnotethatthesedaysmore
complexJavaprojectsoftenuseMaven,whichaddsmanyother
projectmanagementcapabilities.SinceIhadtopickone,inthe
spiritofkeepingthingssimpleandtruetowhatIfinduseful,I
wentwithAntfortheseexamples.)
IfyouarecurrentlyusingMavenasabuildtool,youwillnotice
thatweareusingMaven'sAntTaskstomanagedependencies
fromourAntbuilds.AlthoughMavenisgainingmomentum,Ant
continuestobethemostwidelyusedbuildtoolinJava
development.Everychapter'sexamplecodefolderalsohasa
Mavenpom.xmlfileandcanbecompiledwithMaven.Inmany
cases,theMavenbuildfileprovidesthesamefunctionalityas

theAntbuild.xmlfilebyusingtheMavenHibernate3plug-in.In
Chapter12youwillfindsomeguidanceforbuildingand
deployingHibernateapplicationsusingfull-blownMaven,but
themajorityoftheexamplesinthisbookfocusonAntasa
buildtool,usingtheMavenAntTaskstorelievethetediumof
findinganddownloadingthevariouslibrariesweneed,andthe
librariesonwhichthey,inturn,rely.
Totakeadvantageofallthesecapabilities,youneedtohave


Antinstalledandworkingonyoursystem.

NOTE
IusedtowonderwhypeoplebotheredwithAntwhen
theycoulduseMake.NowthatI'veseenhowwellAnt
managesJavabuilds,Ifeellostwithoutit.

1.1.2.HowdoIdothat?
YoucandownloadabinaryreleaseofAntfrom
Scrolldowntofindthe
currentreleaseofAnt,anddownloadthearchiveinaformat
that'sconvenientforyoutoworkwith.Pickanappropriate
placeforittolive,andexpandthearchivethere.Thedirectory
intowhichyou'veexpandedthearchiveisreferredtoas
ANT_HOME.Let'ssayyou'veexpandedthearchiveintothe
directory/usr/local/apache-ant-1.7.0;youmaywanttocreatea
symboliclinktomakeiteasiertoworkwithandtoavoidthe
needtochangeanyenvironmentconfigurationwhenyou
upgradetoanewerversion:
/usr/local%ln-sapache-ant-1.7.0ant


OnceAntissituated,youneedtodoacoupleofthingstomake
itworkcorrectly.Youneedtoadditsbindirectoryinthe
distribution(inthisexample,/usr/local/ant/bin)toyour
commandpath.Youalsoneedtosettheenvironmentvariable
ANT_HOMEtothetop-leveldirectoryyouinstalled(inthis
example,/usr/local/ant).Detailsabouthowtoperformthese
stepsunderdifferentoperatingsystemscanbefoundintheAnt
manual(ifyouneedthem.


Part1:HibernateinaHurry
OurfirstgoalistogetuptospeedwithHibernateasquickly
aspossible.Mostofthechaptersinthispartareupdated
versionsofcontentfromHibernate:ADeveloper'sNotebook
(O'Reilly),reflectingthemajorchangesthatcameabout
withHibernate3.Thesamplecodenowworkswiththe
latestversionsofthetoolswerelyontoprovideaneasy
yetrealisticenvironmentforworkingwithHibernate.There
isalsoanewchaptercoveringtheabilitytouseJava5
annotations,ratherthanXMLmappingfiles,toconfigure
Hibernatemappings.

NOTE
Ofcourse,withanyprintedbookaboutactiveopen
sourceprojects,thingswillgetoutofdatequickly!
SeeAppendixEforthespecificversionswediscuss,
andforideasonhowtocopewithchanges.
Gettingstartedandfollowingalongwiththeexamplesis
eveneasierinthisnewversionofthebookbecausewe've

adoptedMaventohelpdownloadmanyofthetoolsand
libraries.Aswehopeyouwillsee,there'snoexcuseto
avoiddivinginandtryingthisstuffyourself!
Onceyou'recomfortablewiththefundamentalsof
Hibernate,Part2willdemonstratehowtotieHibernateinto
someotherenvironmentstomakeeachmorepowerfulthan
theyareontheirown.
Allright,timetodivein….


Chapter1.InstallationandSetup
Itcontinuestoamazemehowmanygreat,free,opensource
Java™toolsareoutthere.WhenIneededalightweight
object/relationalmappingserviceforaJSPe-commerceproject
attheturnofthemillennium,Ihadtobuildmyown.Itevolved
overtheyears,developedsomecoolanduniquefeatures,and
we'veuseditinawidevarietyofdifferentcontexts.But,onceI
discoveredHibernate,weusedthatfornewdevelopment
insteadofmyownfamiliarsystem(towardwhichI'llcheerfully
admitbias).Thatshouldtellyouhowcompellingitis!
Ifyou'relookingatthisbook,you'relikelyinterestedina
powerfulandconvenientwaytobridgetheworldsofJava
objectsandrelationaldatabases.Hibernatefillsthatrolevery
nicely,withoutbeingsocomplicatedthatlearningitbecomesa
dauntingchallengeinitself.Todemonstratethat,thischapter
guidesyoutothepointwhereyoucanplaywithHibernateand
seeforyourselfwhyit'ssoexciting.
LaterchapterswilllookatusingHibernateaspartofmore
complexenvironmentssuchasSpringandStripes,aswellas
usingitwithotherdatabases.Thegoalofthisfirstchapteristo

showyouhoweasyitistoputtogetherabasic,self-contained
environmentinwhichyoucanexploreHibernateanddoreal
thingswithit.

1.1.GettinganAntDistribution
Althoughitmightbesurprising,thefirstfewthingsyouneedto
getHibernaterunninghavenothingtodowithHibernateitself.
First,youmustsetupanenvironmentinwhichtheremaining
exampleswork.Thiswillhavethepleasantsideeffectof
buildingasolidfoundationforanyactualprojectyoumightbe
undertaking.
Ifyou'renotalreadyusingAnttomanagethebuilding,testing,
running,andpackagingofyourJavaprojects,nowisthetime


tostart.TheexamplesinthisbookareAnt-driven,soyou'll
needaworkingAntinstallationtorunthemandexperiment
withvariationsonyourownsystem,whichisthebestwayto
learn.
Firstofall,getanAntbinaryandinstallit.

1.1.1.WhydoIcare?
TheexamplesuseApacheAntforseveralreasons.It's
convenientandpowerful;it'soneofthestandardbuildtoolsfor
Java-baseddevelopment;it'sfree;andit'scross-platform.If
youuseAnt,theexampleswillworkequallywellanywhere
there'saJavaenvironment,whichmeansreadersofthisbook
won'tbefrustratedorannoyed.Fortunately,italsomeanswe
candomanymorecoolthingswithlesseffort—especiallysince
severalHibernatetoolshaveexplicitAntsupport,whichI'll

showyouhowtoleverage.(Ishouldnotethatthesedaysmore
complexJavaprojectsoftenuseMaven,whichaddsmanyother
projectmanagementcapabilities.SinceIhadtopickone,inthe
spiritofkeepingthingssimpleandtruetowhatIfinduseful,I
wentwithAntfortheseexamples.)
IfyouarecurrentlyusingMavenasabuildtool,youwillnotice
thatweareusingMaven'sAntTaskstomanagedependencies
fromourAntbuilds.AlthoughMavenisgainingmomentum,Ant
continuestobethemostwidelyusedbuildtoolinJava
development.Everychapter'sexamplecodefolderalsohasa
Mavenpom.xmlfileandcanbecompiledwithMaven.Inmany
cases,theMavenbuildfileprovidesthesamefunctionalityas
theAntbuild.xmlfilebyusingtheMavenHibernate3plug-in.In
Chapter12youwillfindsomeguidanceforbuildingand
deployingHibernateapplicationsusingfull-blownMaven,but
themajorityoftheexamplesinthisbookfocusonAntasa
buildtool,usingtheMavenAntTaskstorelievethetediumof
findinganddownloadingthevariouslibrariesweneed,andthe
librariesonwhichthey,inturn,rely.
Totakeadvantageofallthesecapabilities,youneedtohave


Antinstalledandworkingonyoursystem.

NOTE
IusedtowonderwhypeoplebotheredwithAntwhen
theycoulduseMake.NowthatI'veseenhowwellAnt
managesJavabuilds,Ifeellostwithoutit.

1.1.2.HowdoIdothat?

YoucandownloadabinaryreleaseofAntfrom
Scrolldowntofindthe
currentreleaseofAnt,anddownloadthearchiveinaformat
that'sconvenientforyoutoworkwith.Pickanappropriate
placeforittolive,andexpandthearchivethere.Thedirectory
intowhichyou'veexpandedthearchiveisreferredtoas
ANT_HOME.Let'ssayyou'veexpandedthearchiveintothe
directory/usr/local/apache-ant-1.7.0;youmaywanttocreatea
symboliclinktomakeiteasiertoworkwithandtoavoidthe
needtochangeanyenvironmentconfigurationwhenyou
upgradetoanewerversion:
/usr/local%ln-sapache-ant-1.7.0ant

OnceAntissituated,youneedtodoacoupleofthingstomake
itworkcorrectly.Youneedtoadditsbindirectoryinthe
distribution(inthisexample,/usr/local/ant/bin)toyour
commandpath.Youalsoneedtosettheenvironmentvariable
ANT_HOMEtothetop-leveldirectoryyouinstalled(inthis
example,/usr/local/ant).Detailsabouthowtoperformthese
stepsunderdifferentoperatingsystemscanbefoundintheAnt
manual(ifyouneedthem.


Part1:HibernateinaHurry
OurfirstgoalistogetuptospeedwithHibernateasquickly
aspossible.Mostofthechaptersinthispartareupdated
versionsofcontentfromHibernate:ADeveloper'sNotebook
(O'Reilly),reflectingthemajorchangesthatcameabout
withHibernate3.Thesamplecodenowworkswiththe
latestversionsofthetoolswerelyontoprovideaneasy

yetrealisticenvironmentforworkingwithHibernate.There
isalsoanewchaptercoveringtheabilitytouseJava5
annotations,ratherthanXMLmappingfiles,toconfigure
Hibernatemappings.

NOTE
Ofcourse,withanyprintedbookaboutactiveopen
sourceprojects,thingswillgetoutofdatequickly!
SeeAppendixEforthespecificversionswediscuss,
andforideasonhowtocopewithchanges.
Gettingstartedandfollowingalongwiththeexamplesis
eveneasierinthisnewversionofthebookbecausewe've
adoptedMaventohelpdownloadmanyofthetoolsand
libraries.Aswehopeyouwillsee,there'snoexcuseto
avoiddivinginandtryingthisstuffyourself!
Onceyou'recomfortablewiththefundamentalsof
Hibernate,Part2willdemonstratehowtotieHibernateinto
someotherenvironmentstomakeeachmorepowerfulthan
theyareontheirown.
Allright,timetodivein….


Chapter1.InstallationandSetup
Itcontinuestoamazemehowmanygreat,free,opensource
Java™toolsareoutthere.WhenIneededalightweight
object/relationalmappingserviceforaJSPe-commerceproject
attheturnofthemillennium,Ihadtobuildmyown.Itevolved
overtheyears,developedsomecoolanduniquefeatures,and
we'veuseditinawidevarietyofdifferentcontexts.But,onceI
discoveredHibernate,weusedthatfornewdevelopment

insteadofmyownfamiliarsystem(towardwhichI'llcheerfully
admitbias).Thatshouldtellyouhowcompellingitis!
Ifyou'relookingatthisbook,you'relikelyinterestedina
powerfulandconvenientwaytobridgetheworldsofJava
objectsandrelationaldatabases.Hibernatefillsthatrolevery
nicely,withoutbeingsocomplicatedthatlearningitbecomesa
dauntingchallengeinitself.Todemonstratethat,thischapter
guidesyoutothepointwhereyoucanplaywithHibernateand
seeforyourselfwhyit'ssoexciting.
LaterchapterswilllookatusingHibernateaspartofmore
complexenvironmentssuchasSpringandStripes,aswellas
usingitwithotherdatabases.Thegoalofthisfirstchapteristo
showyouhoweasyitistoputtogetherabasic,self-contained
environmentinwhichyoucanexploreHibernateanddoreal
thingswithit.

1.1.GettinganAntDistribution
Althoughitmightbesurprising,thefirstfewthingsyouneedto
getHibernaterunninghavenothingtodowithHibernateitself.
First,youmustsetupanenvironmentinwhichtheremaining
exampleswork.Thiswillhavethepleasantsideeffectof
buildingasolidfoundationforanyactualprojectyoumightbe
undertaking.
Ifyou'renotalreadyusingAnttomanagethebuilding,testing,
running,andpackagingofyourJavaprojects,nowisthetime


×