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

Agile java development with spring hibernate and eclipse 200

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 (9.69 MB, 657 trang )

AgileJavaDevelopmentwithSpring,Hibernateand
Eclipse
ByAnilHemrajani
...............................................
Publisher:Sams
PubDate:May09,2006
PrintISBN-10:0-672-32896-8
PrintISBN-13:978-0-672-32896-1
Pages:360

TableofContents|Index

AgileJava™DevelopmentWithSpring,HibernateandEclipseisabookaboutrobust
technologiesandeffectivemethodswhichhelpbringsimplicitybackintotheworldof
enterpriseJavadevelopment.Thethreekeytechnologiescoveredinthisbook,theSpring
Framework,HibernateandEclipse,helpreducethecomplexityofenterpriseJava
developmentsignificantly.Furthermore,thesetechnologiesenableplainoldJavaobjects
(POJOs)tobedeployedinlight-weightcontainersversusheavy-handedremoteobjects
thatrequireheavyEJBcontainers.Thisbookalsoextensivelycoverstechnologiessuchas
Ant,JUnit,JSPtaglibrariesandtouchesuponotherareassuchassuchlogging,GUIbased
debugging,monitoringusingJMX,jobscheduling,emailing,andmore.Also,Extreme
Programming(XP),AgileModelDrivenDevelopment(AMDD)andrefactoringaremethods
thatcanexpeditethesoftwaredevelopmentprojectsbyreducingtheamountofupfront
requirementsanddesign;hencethesemethodsareembeddedthroughoutthebookbut
withjustenoughdetailsandexamplestonotsidetrackthefocusofthisbook.Inaddition,
thisbookcontainswellseparated,subjectivematerial(opinionsidebars),comic
illustrations,tipsandtricks,allofwhichprovidereal-worldandpracticalperspectiveson
relevanttopics.Lastbutnotleast,thisbookdemonstratesthecompletelifecycleby
buildingandfollowingasampleapplication,chapter-by-chapter,startingfrom
conceptualizationtoproductionusingthetechnologyandprocessescoveredinthisbook.
Insummary,byusingthetechnologiesandmethodscoveredinthisbook,thereaderwill


beabletoeffectivelydevelopenterprise-classJavaapplications,inanagilemanner!




AgileJavaDevelopmentwithSpring,Hibernateand
Eclipse
ByAnilHemrajani
...............................................
Publisher:Sams
PubDate:May09,2006
PrintISBN-10:0-672-32896-8
PrintISBN-13:978-0-672-32896-1
Pages:360

TableofContents|Index









































Copyright
Forewords
AbouttheAuthor
Acknowledgments

Preface
PartI:Overview
Chapter1.IntroductiontoAgileJavaDevelopment
What'sCoveredinThisChapter
TechnologiesUsedinThisBook
SoftwareDevelopmentMethodologyUsedinThisBook
Summary
RecommendedResources
Chapter2.TheSampleApplication:AnOnlineTimesheetSystem
What'sCoveredinThisChapter
BusinessRequirements
SoftwareDevelopmentMethodology
ApplyingXPandAMDDtoOurSampleApplication
ANoteAboutWikiSoftware
Summary
RecommendedResources
PartII:BuildingtheSampleApplication
Chapter3.XPandAMDD-BasedArchitectureandDesignModeling


















































































What'sCoveredinThisChapter
DesignApproachandArtifactChoices
Free-FormArchitectureDiagram
FromUserStoriestoDesign
ExploringClassesUsingCRCCards
ApplicationFlowMap(HomegrownArtifact)
UMLClassDiagram
UMLPackageDiagram
DirectoryStructure
SampleFileNames
End-to-EndDevelopmentSteps
AcceptanceTests
OtherConsiderations
Summary
RecommendedResources
Chapter4.EnvironmentSetup:JDK,Ant,andJUnit
What'sCoveredinThisChapter
JavaPlatformStandardEditionDevelopmentKit(JDK)
DirectoryStructure
Ant
JUnit
SimpleTest:MakingtheToolsWorkTogether
TestFirstDesignandRefactoring

Summary
RecommendedResources
Chapter5.UsingHibernateforPersistentObjects
What'sCoveredinThisChapter
AnOverviewofObject-RelationalMapping(ORM)
DesignofOurSampleDatabase
WhereHSQLDBandHibernateFitintoOurArchitecture
HSQLDB
WorkingwithHibernate
OtherHibernateFeatures
Summary
RecommendedResources
Chapter6.OverviewoftheSpringFramework
What'sCoveredinThisChapter
WhatIsSpring?




SpringPackagingforDevelopment



SpringPackagingforDeployment














































































OverviewoftheSpringModules
WhereSpringFrameworkFitsintoOurArchitecture
BenefitsofUsingSpring
FundamentalSpringConcepts
SpringSubprojects
Summary
RecommendedResources
Chapter7.TheSpringWebMVCFramework
What'sCoveredinThisChapter
BenefitsoftheSpringWebMVCFramework
SpringWebMVCConcepts
SpringSetupforTimeExpression
DevelopingTimeExpressionUserInterfaceswithSpring
CascadingStyleSheet(CSS)
TimesheetListScreen:ANo-FormControllerExample
EnterHoursScreen:AFormControllerExample
ViewswithNoControllers
SpringHandlerInterceptors
OurSampleApplicationinAction!
NewTagLibrariesinSpringFramework2.0
AWordAboutSpringWebFlowandPortletAPI

Summary
RecommendedResources
Chapter8.TheEclipsePhenomenon!
What'sCoveredinThisChapter
TheEclipseFoundation
TheEclipsePlatformandProjects
EclipseSDKConcepts
InstallingEclipse
SettingUpEclipseforTimeExpression
JavaDevelopmentTools(JDT)Features
InstallingtheEclipseWebToolsPlatform(WTP)Plug-ins
UsingEclipseforTimeExpression
MoreEclipse?Yes,Plug-insGalore!
EclipseTeamSupport
EclipseHelpSystem




TipsandTricks




UninstallingEclipse
AnUnfairComparisontoIntelliJandNetBeans











































































Summary
RecommendedResources
PartIII:AdvancedFeatures
Chapter9.Logging,Debugging,Monitoring,andProfiling
What'sCoveredinThisChapter
LoggingOverview
JakartaCommonsLogging(withLog4jandJDKLogging)
DebuggingJavaApplicationsUsingEclipse
DebuggingWebUserInterfacesUsingFirefox
DebuggingTimesheetManagerTestEnd-to-End(BrowsertoDatabase)
JMXManagementandMonitoring
JavaProfilers
DebuggingTips
Summary
RecommendedResources
Chapter10.BeyondtheBasics
What'sCoveredinThisChapter
RecentlyAddedJavaFeatures
AntTasks
JUnit
Hibernate
TheSpringFramework

TheSpringandHibernateHarmony
JSPTagLibraries
Refactoring
OtherConsiderations
Clustering
Multithreading
ANoteAboutJavaGUI(ThickClient)Applications
ConfigurationManagement(CM)Environments
AsynchronousJavaScriptandXML(AJaX)
JavadocandComments
EntireSysteminOneWARFile!
Summary
RecommendedResources




Chapter11.WhatNext?



What'sCoveredinThisChapter




CompletetheTimeExpressionApplication
XPandAMDD-BasedSoftwareDevelopment







































































JavaPlatform
Ant
JUnit
Hibernate
TheSpringFramework
EclipseSDK
Logging,Debugging,Monitoring,andProfiling
GettingHelp
AQuickNoteAboutCode"Quality"Tools
Summary
RecommendedResources
Chapter12.PartingThoughts
MyNearFuturePlans
TheFuture,AgileMethods,JavaTechnology
Cheers!
PartIV:Appendices
AppendixA.DownloadableCodeforThisBook
Third-PartyLibrariesSharedDirectory
SampleApplicationDirectory(rapidjava/timex/)
RefactoredSampleApplicationDirectory(rapidjava/timex2/)
Spring-HibernateIntegrationDemoDirectory(rapidjava/springhibernate/)
AppendixB.RefactoringDonetoSampleApplication
SignInController.java:JMXMonitoring
TimesheetListController.java:JMXMonitoring

ManagerClasses:Spring-HibernateIntegration
timesheetlist.jsp:SwitchtoIncludeFileandDisplaytag
enterhours.jsp:SwithtoIncludeFileandTimexTagLibrary
*TestClassesandTimexTestCase
DateUtil.java:NewMethod
timex.css:NewStyles
timexhsqldb.xml:BadDataDefectFix
AppendixC.JavaCodeConventions
AppendixD.SecuringWebApplications












































AppendixE.SampleDevelopmentProcessCheatSheet
ProjectInitiation
ExplorationPhase
Planning
IncrementallyBuildSoftwareinIterations
AppendixF.AgileModelingValues,Practices,andPrinciplesCheatSheet
AppendixG.ExtremeProgramming(XP)CheatSheet
Overview

AppendixH.CoolTools
Cross-PlatformTools
MicrosoftWindows-BasedTools
MacOSX-BasedTools
Linux-BasedTools(KDE)
AppendixI.VisualPatternsResearch
TheProblem
ThePast:HowWeHaveBeenKiddingOurselves
TheFuture:AgileMethods
MyPerspective
JointheCommunity?
Index


Copyright
AgileJavaDevelopmentwithSpring,Hibernateand
Eclipse
Copyright©2006bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbereproduced,
storedinaretrievalsystem,ortransmittedbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,
withoutwrittenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseoftheinformation
containedherein.Althougheveryprecautionhasbeentakenin
thepreparationofthisbook,thepublisherandauthorassume
noresponsibilityforerrorsoromissions.Norisanyliability
assumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2005937888
PrintedintheUnitedStatesofAmerica

FirstPrinting:May2006
090807064321

Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttotheaccuracyof
thisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservice
mark.


WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookascompleteand
asaccurateaspossible,butnowarrantyorfitnessisimplied.
Theinformationprovidedisonan"asis"basis.Theauthorand
thepublishershallhaveneitherliabilitynorresponsibilitytoany
personorentitywithrespecttoanylossordamagesarising
fromtheinformationcontainedinthisbook.

BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontact
U.S.CorporateandGovernmentSales
1-800-382-3419

ForsalesoutsideoftheU.S.,pleasecontact
InternationalSales


AcquisitionsEditorJennyWatson
DevelopmentEditorsScottMeyersSonglinQiu
ManagingEditorPatrickKanouse
ProjectEditorMandieFrank
CopyEditorBarbaraHacha
IndexerCherylLenser
ProofreaderKathyBidwell
TechnicalEditorBorisMinkin
PublishingCoordinatorVanessaEvans
BookDesignerGaryAdair


PageLayoutNonieRatcliff
AgileJavaDevelopmentwithSpring,Hibernate,and
Eclipseisawell-writtenguidethatcoversnumerous
significanttechnologies,weavingthemtogetherusing
practicalandprovenmethodsthatwillsurelyprovide
valuetopractitionersofeverylevel.
DanMalks,VPSolutions&StrategicDevelopment,JackBe
Inc;Author,CoreJ2EEPatterns
Anil'srelentlessdedicationtohighqualityreallyshows.
Thisisaverywell-writtenbook!
MadhuSiddalingaiah,Consultant(madhu.com)
Anilhasanuncannyabilitytocuttothechaseandtellyou
whatyouwanttoknow.Thisbookisoneofthosejewels
thatappearsonlyinfrequently.Insteadofvoluminous
explanationsofAPIs,Anilprovidesinsightfulinterpretation
inhighlyvisualterms,withasimpleexamplethatthreads
allthewaythroughthebook.Itisamasterworkof
usability,ascomputerbooksgo.

CliffBerg,founderofAssuredbyDesign,co-founderof
DigitalFocus,authorandconsultant

Dedication
Thisisdedicatedtomylovingandcaringwifewhohasalways
patientlysupportedme(andmyoddways).Thankyoufor
takingcareofeverythingduringthetimesIwasconsumedby
projectssuchasthisbook.Thisbookwouldnotbepossible
withoutyou!And,ofcourse,tomydearestkidswhobrighten
myeveryday.


Forewords
Thetruegoalofaforewordistoconvincepeopletopurchase
thebook.So,Iguessyouhavethreechoicesrightnow.First,
youcansaveyourselfsometime,stopreadingthisforeword
rightnow,andsimplytakemywordforitthatbuyingthisbook
isagoodwaytoinvestyourhard-earnedmoney.Second,you
couldnottrustme,whichfranklyisasmartthingtodobecause
I'maconsultant,andcontinuereadingthisforewordonthe
chanceImightactuallysaysomethingthatresonateswithyou
andtherebymotivateyoutobuythebook.Third,youcould
decidetonotpurchasethebook,whichislikelyareallybad
ideabecausethevastmajorityofJavaprogrammersthatIhave
metcouldreallybenefitfromthismaterial.
Inmyopinion,thelastthingthattheJavacommunityneedsis
anotherbookdescribingsome"reallycool"Javatechnologies;
therearehundredsofbooksouttherealready,thousandsof
magazinearticles,andtensofthousandsofwebpagesalready
coveringreallycoolJavatechnologies.Luckily,that'snotwhat

thisbookisabout.AgileJavaDevelopmentisoneofthoserare
booksthatteachesskillsthatyouwillusethroughoutyour
career.Yes,itdoescoverthefundamentalsofSpring,
Hibernate,Ant,andabunchofotherstuffthatyouneedto
succeedtoday.But,moreimportantly,itgoesbeyondthe
technologytodescribeagiletechniques,adoptedfromExtreme
Programming(XP)andAgileModeling(AM),whichenableyou
tosucceedatmodernsoftwaredevelopment.
MostJavadevelopershaveheardaboutXPandmanyhave
adoptedsomeofitstechniques,suchastest-drivendesign
(TDD),refactoring,andevenpairprogramming.Thisisagood
start,butit'snotenough.Inthisbook,Anilbringshisyearsof
experiencetothetable,describingwhatactuallyworksin
practice.Thisisdifferentfromotherbooksthatoftensharea


visionofwhattheauthorthinkswillworkintheory;butaswe
allknow,theoryandpracticeareoftentwodifferentthings.
WhenAnilfirstapproachedmetobeatechnicalreviewerofthis
book,thethingthatmostimpressedmewashissimple,yet
effective,approachtomodelingonJavaprojects.Infact,you
mightwanttoflipthroughthebookrightnowandtakeaquick
lookatsomeofthemodels.Ithinkthatyou'llnoticethathis
diagramsareverysimilartowhatyoudevelopyourselfon
actualprojectsarefreshingchangefromtheadvicepresentedin
manyofthemodelingbooksavailabletoday.You'llalsonotice
howAnildescribeshowtomovefromthosesimplemodelsto
theoften-complexcodethatyouwriteonadailybasis.ThisI
thinkrepresentsthegreateststrengthofthisbook:itpresents
real-worldadvicethatreflectswhattop-notchdevelopers

actuallydoinpractice.
Thebookalsoshowshowmanyofthecommontasksthatwe
perform,suchasacceptancetesting,unittesting,
object/relationalmapping,systemintegration,andrefactoring,
fitintothesoftwaredevelopmentpicture.Thebookstartswith
the"5,000foot"processpointofview,butdivesdownto
groundlevelanddescribeshowtousethetoolsinpractice.
Mostbooksfocusononeviewbutnottheother,butAgileJava
Developmentpullsitoffnicelyandcoversbothviewswell.Take
afewminutesandbrowsetherestofthisbook.Ithinkyou'll
seewhatI'mtalkingabout.
ScottW.Ambler
PracticeLeader,AgileModeling
Thisbookisnoteasilycategorized.Letmeexplainwhyit's
unusual,andwhyitdeservesyourattention.
Easilycategorizablebooksaboundinourindustry.Theyare
oftenbooksaboutaparticularproductorAPI.Somearegood;


somearebad.Youcanchoosebythecover,thefont,the
publisher,thecredibilityoftheauthorbutyouhavealready
madeafarmoreimportantchoice:Youknowwhatbookyou
arelookingfor.Agoodsuchcommoditybookmaymakeyou
moreefficientinaparticulararea,butit'sunlikelytochange
thewayyouwork.
Booksthatarenoteasilycategorizablearemuchrarer.They
relatemuchmorecloselytotheirauthor,andpotentiallytoyou.
Thepresentbookshowshowvaluablesuchabookcanbe.Anil
Hemrajanihasdistilledhisextensiveexperienceasanarchitect
anddeveloperintoabookthataboundsinthepracticalinsights

ofasuccessfulpractitioner.Likeallthebestbooks,it'san
effectivecommunicationbetweenauthorandreader.Aswithall
effectivecommunication,thetopicisnotlimitedtothe
predictable,andit'senjoyable:Anilhasanaturalwritingstyle
thatisapleasuretoread.
Thisbookhasaremarkablybroadscope.Ittacklestopicsthat
arerarelytackledtogether,butshouldbe.Theprocessweuse
todevelopsoftwareisinextricablylinkedtothewayinwhichwe
structureourcodeandthetoolsweusetowritethatcode.No
effectivedeveloperworksinacompartmentalizedfashionthe
manydecisionstobemadeareintertwinedbutmostbooks
makelittleattempttopaintthebigpicturethatisessentialto
gettingresults.
TodevelopJavasoftwareproductivelytoday,youneedto
understandkeyconceptssuchasO/RmappingandDependency
Injection;youneedtounderstandhowandwhytouse
techniquessuchasunittestingandautomatedbuilds;
andequallysignificantyouneedtoknowthebesttoolsforthe
job,suchasframeworksandIDEs.Youalsoneedtounderstand
someofthepitfallstoavoid,andhowsometimessoftskillsare
ascriticalastechnology.
Anilhasdonearemarkablejobofbringingthesethings


togetherintoabookthatprovidesclarityinanareathatmany
findconfusing.Itcoversalotofground,butneverlosessightof
itsaimtohelpreaderscompletesuccessfulprojects.
Iseethisbookasagoodmap.Itclearlyshowsyouthepathon
yourjourneytosuccessfulenterpriseJavadevelopment.Along
theway,youmaysupplementitwithmoredetailedmapsof

particularareas.Butyouwillalwaysbenefitfromthedirectionit
provides.
Irecommendthisbooktoanyonesettingouttobecomean
enterpriseJavapractitionertoday.Itmaywellchangetheway
youwork,forthebetter.
RodJohnson
CEO,Interface21
Founder,SpringFramework




AbouttheAuthor
AnilHemrajanihasbeenworkingwithJavaTechnologysince
late1995asadeveloper,entrepreneur,author,andtrainer.He
isthefounderofIsavixCorporation,asuccessfulITservice
company(nowInscopeSolutions),andisavix.net(now
DeveloperHub.com),anaward-winningonlinedeveloper
communitythatgrewtomorethan100,000registered
members.Hehas20yearsofexperienceintheinformation
technologycommunityworkingwithseveralFortune100
companiesandalsosmallerorganizations.Hehaspublished
numerousarticlesinwell-knowntradejournals,presentedat
conferencesandseminarsaroundtheworld,andreceivedthe
"OutstandingContributiontotheGrowthoftheJava
Community"awardfromSunMicrosystems,the"BestJava
Client"awardatJavaOneforBackOnline,aJava-basedonline
backupclient/serverproduct,andwasnominatedfora
Computerworld-Smithsonianawardforafreeonlinefilestorage
servicewebsite.Hismorerecentprojectisthe

visualpatterns.comwebsite.




Acknowledgments
Iwrotethisbookbutitwouldn'thavebeenpossiblewithoutthe
helpofmanybrilliantpeopleIhavethedistinctpleasureof
knowing.Itrulywanttothankeveryonelistedhere,fromthe
bottomofmyheart!
CliffBergFirstandforemost,IwanttothankCliff,alongtimefriendandcolleague,forinspiringmetowritethis
bookandgivingmetheconfidencebyvalidatingand
supportingmyideas.
ScottW.AmblerForagreeingtoco-writetheforewordfor
thisbookandreviewingeverysingleelementinit,chapter
bychapter.Scotthasbecomeoneofmyidolsinthisfield,
givenhisworkonAgileModelingandAgileData,soI'mstill
amazedthatheagreedtogetinvolvedwiththisbook
consideringhowenormouslybusyheis.Ialsowantto
thankScottforthewww.agilemodeling.comand
www.agiledata.orgwebsites;thesehavebeeninvaluablefor
me.Scott,thankyou.
RodJohnsonWhenIfirstmetRod,IhadnoideaIwouldbe
writingthisbookoraskinghimforaforewordIjustknew
wesharedsimilarviewsandIrespectedhisworkalot.
GiventheSpringFramework'spopularitythesedays,I'm
surprisedthatRodevenfindstimetosleep,sofittinginthe
forewordformybookwasespeciallymeaningfultome
(thankyou!).IalsowanttothankRodforputtingtogether
theSpringFramework,somethingI'veenjoyedworking

with.
AnilSinghIcannotevenbegintothank(theother)Anilfor
hishelp;thelonghours,theinvaluablefeedback,thelate


nightsoverthephonediscussingthecontentsofmy
chapters(3a.m.attimes)thanksforeverything!I
particularlyappreciateAnil'savailabilityalmostanyand
everytime,todiscussmybook.Yet,allIcanofferinreturn
isaheartwarmingthankyou!
DanShellmanForhisrapidbutdetailedandhonest
feedback,whichhelpedmakethisbooksomuchbetter.
Thanksfortoleratingthe100orsoemailsIsentoverthe
courseofthisbook.Iparticularlyappreciateyourfeedback
andtelephoneconversationsonweekendsandevenon
familyvacations!Danhasbeenalong-timecolleagueand
friendandIhopethisremainsthecaseforalongtimeto
come.
HareshLalaForhisconstantfeedbackonanythingand
everything!Thanksfortestingallmycode(twice!)and
readingmychaptersintheirearliest,veryrough,draft
form.Mostofall,thankyouforhelpingmeduringatime
whenyouweresuperbusywithnewthingsinyourlife.
HernandoVeraWhatwouldIdowithoutHernando'sastute
thinking,clearpresentationofideas,andwell-thought-out
interpretationoftechnologies?Hernandohasbeenoneof
my"goto"guysforalmostadecadenow.WhenI'min
doubt,IknowIcanturntohimforanswersfrom
developmenttodesigntoarchitecturetoprocessandmore.
Ihaveyettomeetanyoneelsethathasthefullpackage:

brilliant,innovative,current,andmostofalloneofthe
nicestpeopleIknow.
MartinRemmelzwaalMartinandImetrelativelyrecently
butIalreadyconsiderhimaclosefriend.Thanksfor
reviewingmyearlierchapters.However,Iparticularlywant
tothankyouforrespondingtomyneverendingemails
aboutyourperspectiveonvarioustechnology,and


methodology,relatedmatters.Ihopetocollaboratewith
Martinonvariousprojectsinthefuture.
TheSpringFrameworkteamFirstofall,youguysare
simplyawesome!Now,forspecificnames.Iwanttothank
AlefArendsenforhisreviewofChapters6and7and
assistanceingeneralwithanythingandeverythingSpring;
Alef'sreviewsignificantlyimprovedChapters6and7.Ialso
wanttothankJuergenHoellerforhishelpondeclarative
transactionmanagementandlatediscussionsabout
interfaces.Giventhespringteam'sdayjobs(helping
clients),nightjobs(workingontheframework),and
jugglingmultiplereleasesatthesametimewell,whatcanI
saybutthanks,guys!
MadhuSiddalingaiahForhisguidanceindraftingupthe
outlineofthisbook(andotherpublishingmatters),andalso
forhisvaluablefeedbackonChapter8.
DaveBermanDave'sin-depthreviewofChapter2and
variousdiscussionsaboutAgilemethodshelpedmakethe
Agile/XPaspectsofthisbookmoresolidandthorough.
JeffNielsenForhistimelyfeedbackonmydiagramsin
Chapter2and3andtheXP+AMDDcomicseriesusedin

thisbook;Iwasabletofixsomemajorerrorsinthenickof
time,thankstoJeff!
RamanandSinghForourinitialdiscussionsaboutSpring
andfeedbackonChapter6.
PearsonstaffIwanttothankthestaffatPearson(Songlin,
Mandie,Kim,Mark,Barbara,andseveralothersbehindthe
scenes)forproducingthisbook;aspecialthankstoJenny
forherinvolvementfrombeginningtoend;herbeingthere
helpedmeduringnormalandfrustratingtimes.Ialsowant


tothankBorisforhisin-depth,direct,andvaluablereview
ofthisbookthisbookwouldn'tbewhatitiswithouthishelp.
TomyfriendPeter,thanksfortheintellectualstimulusfrom
timetotime,whichhelpedmeapproachthebookfrom
uniqueperspectives.Also,combinedwithAndyandMissy,
thanksforallthelaughs,whichhelpedmeletlooseabit
whenIneededitmost(particularlyduringtheweeksof
continuous14-to15-hourdayswritingthisbook).
TotheGreenberry'scoffeeandteashopstaffforprovidinga
comfortableenvironment,high-speedinternet,andgreat
coffeeandfood;alloftheseallowedmetoworktherefor
hoursatatimeonthisbook.
Lastbutnotleast,thisbookisbasedontheinnovativework
ofmanypeopleinourindustrywhohavebecomemyidols,
sotospeak.Iwouldliketothankthesepeople,because
theyhelpedmeindirectlybycontributingsomeinvaluable
andamazingconcepts.SomeofthesepeopleincludeMartin
Fowler,KentBeck,EricGamma,WardCunningham,and
others.


WeWanttoHearfromYou!
Asthereaderofthisbook,youareourmostimportantcritic
andcommentator.Wevalueyouropinionandwanttoknow
whatwe'redoingright,whatwecoulddobetter,whatareas
you'dliketoseeuspublishin,andanyotherwordsofwisdom
you'rewillingtopassourway.
Youcanemailorwritemedirectlytoletmeknowwhatyoudid
ordidn'tlikeaboutthisbookaswellaswhatwecandotomake
ourbooksstronger.
PleasenotethatIcannothelpyouwithtechnicalproblems


relatedtothetopicofthisbook,andthatduetothehigh
volumeofmailIreceive,Imightnotbeabletoreplytoevery
message.
Whenyouwrite,pleasebesuretoincludethisbook'stitleand
authoraswellasyournameandphoneoremailaddress.Iwill
carefullyreviewyourcommentsandsharethemwiththeauthor
andeditorswhoworkedonthebook.
E-mail:



Mail:

MarkTaber







AssociatePublisher
PearsonEducation
800East96thStreet
Indianapolis,IN46240USA

ReaderServices
Visitourwebsiteandregisterthisbookat
www.samspublishing.com/registerforconvenientaccesstoany
updates,downloads,orerratathatmightbeavailableforthis
book.


Preface
IBEGANWORKINGWITHJAVATECHNOLOGYinlate1995,
shortlybeforetheJavaDevelopmentKit(JDK)1.0wasformally
released.Priortothat,IwasprogramminginCandC++for
manyyears.IwastrulyexcitedaboutthefeaturesthatJava
offered,suchascross-platformportability,simplersyntax
(simplerthanC++,forexample),objectoriented,secure,rich
API,andmore.
Overmy20-yearcareer,Ihavelearnedafewthings.Among
these,myfavoriteissimplicity;anytimeIseecomplexity,I
begindoubtingwhetherthesolutioniscorrect.ThisishowIhad
beguntofeelaboutJavarightaround2000,whentheJava2
EnterpriseEdition(J2EE)startedbecomingmainstream.Note
thatfromthispointon,IwillrefertoJ2EEasJEEbecausethe
"2"wasrecentlydroppedfromthenamebySunMicrosystems.

MygrowinglackofinterestinJavawasaresultofwhatIsaw
asunnecessarycomplexityinJEEintroducedbylayersof
abstraction.IbegantobelievethatSunMicrosystems(inventor
ofJava)wasfocusingJavaandJEEonsolvingthemostcomplex
enterpriseapplications,butsomewhatignoringtherelatively
lesscomplex,small-tomedium-sizedapplications.
Furthermore,Isawthehypetakeoverpeople'scommonsense
becauseIranacrossprojectsinwhichEnterpriseJavaBeans
(EJB)wereusedfornondistributedprocessing,suchaslocal
logging.Ifeltstronglyenoughaboutthissubjecttowritea
shortarticleforJavaWorld.comin2000
(titled,"DoYouReallyNeedEnterprise
JavaBeans?"(Aboutfiveyearslater,wesawEJB3.0
specificationsbeingrewrittentobecomemoresimplified,to
easethedevelopment.)Thisbringsustothisbookandthe
reasonIwroteit.


IwasrecentlyhiredasaconsultantforaFortune100company
tobuildanenterprisewebapplicationrunninginaclustered
environment.Whilereviewingalternativestothestandard
JEE/EJBmodelbyresearchingonlineandhavingdiscussions
withsomesmartpeople,Idecidedonasolution,whichincluded
theSpringMVCwebframework,Hibernateobject-relational
(OR)persistenceframework,theEclipseIDE,JUnittesting
framework,Antbuildutility,severaltaglibraries,andafew
otherproducts.(Alltheseproductsarecoveredindetaillaterin
thisbook,alongwithmyrationaleforchoosingthese
technologies.)
IhaveenjoyedworkingwithSpringandHibernate,mainly

becausetheyallowmetoworkwithplain-oldJavaobjects
(POJOs)andavoidsomeofthehasslesofworkingwithEJBs.
Also,workingwiththeEclipseIDEhasbeenaniceexperience.I
continuetobeamazedathowwellthisproductworks,andthat
isthereasonIdedicateawholechapterinthisbooktoit.Inmy
opinion,productssuchastheonesmentionedhereare
breathingnewlifeintoJavaatatimewhenJavaisatriskof
losingitspopularitytoalternativessuchasMicrosoft's.NET,
LAMP(Linux,Apache,MySQL,andPHPorPython/PERL),and
RubyonRails.
Inthisbook,althoughSpring,Hibernate,andEclipseare
highlighted,akeygoalformeistoprovideyouwithacomplete
solutionfromtechnicalandprocessperspectives.Froma
technicalperspective,Iprovideanend-to-endsolution(usinga
varietyoftools)forimplementingacompletesampleweb
applicationwithtransactionmanagementinthebackendand
suitableforaclusteredenvironment.Fromaprocess
perspective,IrecentlyswitchedfromusingtheRationalUnified
Process(RUP)toaprocesscomposedofguidelinesprovidedby
AgileModelDrivenDevelopment(AMDD;agilemodeling.com)
andExtremeProgramming(XP;extremeprogramming.org).As
aresult,inthisbookyouwillfindconceptsandartifactssuchas
userstories,releaseplans,CRCcards,andmore.Theideaisto


provideyouwithacomprehensivesolutionforrapidly
developinganddeployingenterpriseJavaapplications.
Oneadditionalnoteaboutmybackground.Ihavebeena
developerforalmost20years,primarilyworkingwithcore
technologiessuchasC/C++,Java,enterpriserelational

databases,applicationservers,Unix,MicrosoftWindows,andso
on.However,Itookadetourforapproximatelyfiveyears
around1998tobuildthecompanyIhadfoundedin1996(Iwas
doingminimalprogrammingduringthistime).Ilatersoldthis
companytogetbackintodevelopment.However,eventhoughI
wastheCEOofthiscompanyandhadseveralpeopleworking
forme,Igottheopportunitytomeetandinterviewliterally
hundredsofdevelopersoveraseven-yearperiodanddiscuss
technologywiththem.Apartfromthiscompany,Ialsofounded
anonlinecommunityforJavadevelopers,grewittoover
100,000members,andwonseveralawardsforthis.Ihopemy
experiencefromtheseventuresaddsauniqueperspectiveto
thisbook.
Insummary,Itrulyhopeyouwillfindthisbookusefulandwill
enjoyreadingit!

WhoThisBookIsFor
Thisbookassumesthatyouhavesomeworkingknowledgeof
Javaandrelationaldatabases(includingSQL)aswellas
experienceworkingonthecommandline.Asidefrom
prerequisitesmentionedhere,thefollowingtypesofpeoplecan
useit:
SoftwareDevelopers/ArchitectsDevelopersandarchitects
cangainvaluefromthisbookbecauseitincludesahighlevelsoftwaredevelopmentprocess,applicationdesign,and
anin-depthandcompleteinspectionoftheJavaandrelated
filesofafullyfunctional,sampleenterprisewebapplication.


TechnicalLeads/ManagersTechnicalleadsandmanagers
withaprogrammingbackground,preferablyinJavaor

similarlanguage,cangetanin-depthlookathow
applicationsarebuiltusingavarietyofJavatechnologies.
Thisknowledgemighthelpduringprojectplanningorwith
stafftroubleshootingtechnicalproblems(perhapsjustfor
moralsupportduringfrustratingtimes).Alternatively,
technicalmanagerscandiveintoaspecificchapter(for
example,Chapter5,"UsingHibernateforPersistent
Objects")tounderstandhowthatspecifictechnologyworks
andfitsintothebigpicture.
Inaddition,asareader,youmightgainsomeinsightfromthis
bookonalternativestoJEEthatyoucanuseforbuildinga
robustenterprise-classapplication.Furthermore,ifyouarenot
familiarwithAgileModelingorExtremeProgrammingorare
lookingforanimblesoftwaredevelopmentprocess,thisbook
mighthavejustenoughtogetyougoingwithacomplete
processfordevelopingsoftwareapplicationsiterativelyand
incrementally.

GoalsofThisBook
Thegoalsofthisbookareasfollows:
AgiledevelopmentThefirstandforemostgoalofthisbook
istoshowyouhowtodorapidenterpriseJava
development.Thisisachievedbycombiningmultiplefacets:
animble/minimalsoftwaredevelopmentprocess,asimple
design(moderateuseofdesignpatternsorlayersof
abstraction),conveniencetechnologies(suchasSpringand
Hibernate),workingwithPOJOsversusremoteobjects,and
ingeneral,leveragingstableopensourcetechnologies
wheneverpossible.Inshort,theideaistomakeJava
simplerandfastertoworkwithfordevelopingenterprise-



readyapplications.
CompletesolutionAclosesecondgoalofthisbookisto
provideyouwithacompletesolution,fromatechnicaland
processperspective.Afterreadingthisbook,youshouldbe
abletobuildanentireapplication,notjusttechnically,but
alsousingtheprocessoutlinedinthisbook.Inaddition,
whenIcannotcoveragiventechnologyindepth,Iprovide
referencestoresources(websites)forfurtherinvestigation
ofthetechnology.Thecoolthingaboutthetechnologies
coveredinthisbookisthatyoucanhaveacomplete
system,fromtheuserinterfacetoanembeddeddatabase
alongwiththecapabilitytoschedulejobs(thankstothe
SpringFramework),allself-containedinasingleweb
applicationarchive(.war)file!However,youcanalways
replacethetechnologiesmentionedinherewithsomeother
technologyofyourchoice(forexample,usinganOracle
databaseinsteadofHSQLDB).Insummary,youwillhave
thecompletesolutiontodothisprocessandtechnologies!
Usinganopensourceonlysolutionisnotagoalofthisbook
AlthoughIhavebasedthisbookentirelyonopensource
frameworks,tools,andproducts,preachinganopensource
onlysolutionisn'tagoalofthisbook.Forinstance,youcan
leverageJava'svendorportabilityandreplaceoneofthe
productscoveredinherewithacommercialproduct.
However,opensourcehascomeaverylongway,andI'm
thoroughlyimpressedbyhowrobustthesetechnologiesare
andhowwelldocumentedtheyare.Forexample,
technologiessuchastheEclipseSDKandHibernateare

arguablybetterthansomeoftheircommercial
counterparts.Youcouldjustaswelluseallthetechnologies
mentioninthisbookforanenterprisesolutionandrest
assuredthattheywillperformasadvertised.Infact,I
recentlyimplementedanenterprisesolutionforalarge
companyusingtheSpringFramework,Hibernate,Eclipse,
JUnit,Ant,andothertoolsmentionedinthisbook!However,


×