The Spring Framework - Intertech The core of the Spring Framework was initially distributed ......

88
Copyright © Intertech, Inc 2014 Rev: 2 1-1 Chapter 1 The Spring Framework Objectives: Understand the purpose of the Spring Framework. Gain an appreciation for why it exists and why you would use it to build an application. Explore the Spring modules and architecture. See how to obtain the Spring Framework. Glimpse a simple Spring application.

Transcript of The Spring Framework - Intertech The core of the Spring Framework was initially distributed ......

Copyright©Intertech,Inc2014Rev:2 1-1

Chapter 1  

TheSpringFramework

Objectives:

UnderstandthepurposeoftheSpringFramework.

Gainanappreciationforwhyitexistsandwhyyouwoulduseittobuildanapplication.

ExploretheSpringmodulesandarchitecture.

SeehowtoobtaintheSpringFramework.

GlimpseasimpleSpringapplication.

TheSpringFramework

1-2 Copyright©Intertech,Inc2014 Rev:2

ChapterOverview

TheSpringFrameworkhastakentheJavasoftwaredevelopmentcommunitybystorminjustafewshortyears.EvenifaJavadevelopmentteamwerenotusingSpring,itwouldbetoughtofindonethathasn’tatleastheardofSpring.Sowhatisitandwhyhasitbecomesopopular?

Theterm“framework”insoftwareengineeringisoverusedandoftenmisunderstood.Therefore,thisfirstchapteraddressestheimportantquestionsofwhatistheSpringFrameworkandwhyuseitinapplicationdevelopment.YoualsoexploreasimpleSpringapplication.Asyouwillsee,eventhesmallestandsimplestofSpringapplicationscanhighlightSpring’sstrengthinbuildingeasytounderstandandflexibleJavaapplications.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-3

What is Spring? 

• Moreprecisely,whatistheSpringFramework?

• TheSpringFrameworkis“anopensourceapplicationframework.”1

• Opensourcemeansthatitisavailable“free”tothepublicforuseand/ormodification.

• Therearemany“frameworks”intheapplicationdevelopmentcommunity.Mostoftheseframeworkssupportasingletierorareaoftheapplication.

• Forexample,Hibernateisapersistenceframework.StrutsisaWebMVCframework–addressingtheViewandControllayersofanMVCWebapplication.

• Springismeanttoprovideaframeworkforthewholeapplication.

• Aframeworkisn’tanapplicationitself,butprovidesthesupporttobuildanapplication.

• Agoodframeworkprovidesguidanceandstructureaswellassupportingcodeandlibraries.

• ItwasoriginallycreatedbyRodJohnsonandfirstdescribedinhis2002book:ExpertOne‐on‐OneJ2EEDesignandDevelopment.2

• Spring1.0wasreleasedin2004.

• ThelatestreleaseofSpringisversion3.0(December2009).

• GivenitsageincomparisontootherAPIsandtools,itisarelativenewcomertotheframeworklandscape.

• Springisavailablefromwww.springsource.org(alsowww.springframework.org).

1RodJohnsonetal.,JavaDevelopmentwiththeSpringFramework(WileyPublishing,WroxPress,2005),pg1.2RodJohnson,ExpertOne‐on‐OneJ2EEDesignandDevelopment(WileyPublishing,WroxPress,2002).

TheSpringFramework

1-4 Copyright©Intertech,Inc2014 Rev:2

Why use Spring? 

• SpringwascreatedtoreducethecomplexityobservedinJavaenterpriseapplicationdevelopment–mostnotablyinEnterpriseJavaBeandevelopment.

• InJohnson’sownwords,“J2EEapplicationsareovercomplex,takeexcessiveeffort

todevelop,andexhibitdisappointingperformance.”3

• “J2EE‘outofthebox’isnotanattractiveoption.[The]APIsandservicesarecumbersometouse.”

• “J2EEdoesagreatjobofstandardizinglow‐levelinfrastructure”but“J2EEdoesnotprovideaneasilyusableviewforapplicationcode.”

• Thus,Springismeanttobea“lightweight”frameworktogetthebenefitsofJavaEEwhileminimizingthecomplexity.

• Springdoesnotrequirea“heavyweight”container,suchasaJ2EEapplicationserver,torunin.

• Ingeneral,Springleveragesplainordinary(orold)Javaobjects(POJOs)ormorepreciselyJavaBeanstoachieveenterprisetasks.

• Therefore,Springcanalsobeusedinnon‐enterpriseJavaapplications.

• Forexample,SpringcanbeusedinanappletorotherJavaStandardEdition(JavaSE)environment.

3RodJohnsonetal.,JavaDevelopmentwiththeSpringFramework(WileyPublishing,WroxPress,2005),pgs1‐3.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-5

• TheadjectivelightweightwithSpringhasseveralconnotations.

• Yes,Springislightweightinthatitreducescomplexity.

• Itisalsolightweight,literally,initssizeandcodeimpact.

• ThecoreoftheSpringFrameworkwasinitiallydistributedinasingleJARfilethatwasabout2.5MBinsize.

• Today,SpringislargerwithmanyJARfiles,butremainsrelativelylightweightgivenitscapabilities.

• Springalsoworkshardtobenon‐intrusive.Thatis,SpringrarelyrequiresapplicationcodetoextendorimplementSpringclassesorinterfaces.

• ThismakesiteasytoremoveSpringortoincorporateotherbest‐of‐breedframeworkswithoutcausinglargechangestoexistingcode.

• NotethattherearealternativestotheSpringFramework.

• Moreprecisely,therearealternativelightweightopen‐sourceJavaapplicationDI(dependencyinjection)containers/frameworks.

• HiveMind(nowretired)andPicoContainerarealternatives.4

HiveMindwasdevelopedbythecreatorofJakartaTapestry.5

PicoContainerclaimstobethesmallestofthe“lightweightcontainers.”6

• GooglealsohasbuiltalightweightDIframeworkcalledGuice(pronouncedjuice).7

• JavaEEhasevenincorporatedsomeoftheconceptsseeninSpring–likedependencyinjection.

• Springisthelargestandmostfeaturerichoftheapplicationframeworks/containers.

• SpringhasandcontinuestoreceiveoverwhelmingsupportfromthelargerJavacommunity.

4http://www.ibm.com/developerworks/opensource/library/os‐lightweight4/5http://hivemind.apache.org/6http://www.picocontainer.org/7http://code.google.com/p/google‐guice/

TheSpringFramework

1-6 Copyright©Intertech,Inc2014 Rev:2

Spring Philosophies 

• Springisbasedandconstructedonthepremiseofseveralcoredevelopmentphilosophiesorvalues.

• ManyofthesephilosophiesandvalueshaveoriginsinJohnson’sExpertOne‐on‐Onebook.OtherscomedirectlyfromtheSpringFrameworkmissionstatements.8

• Javaenterpriseapplicationsshouldbeeasytocreate.

• Theframeworkshouldbelightweight.Althoughnolongerthecase,itallowedtheframeworktobedistributedinasingleJARfile.

• Theframeworkshouldbenon‐intrusive.“Lock‐in”toSpringshouldbeminimized.

• Forexample,theapplicationcodeshouldnotberequiredtoextendalotofclassesorimplementalotofinterfaces.

8http://www.springsource.org/about

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-7

• OtherprincipalsSpringespouseincludethefollowing:

• Good(andsimple)designshouldnotbecompromisedbecauseoftheunderlyingimplementationtechnology.

• Theframeworkshouldfacilitategoodobject‐orienteddesign/analysis.Again,theapplicationdesignismoreimportantthantheenterprisetechnology.

• Applicationcodeshouldbeeasytotest.Morespecifically,applicationcomponentsshouldbeeasytounittest.

• Theuseofunittestingframeworks(likeJUnit)onapplicationcomponentsshouldbepossibleevenwithoutanenterprisecontainer.

• Alltoooftenwhentestingenterprisecomponents(likeEJBs),theenterpriseserverenvironmentmustbeavailabletotesteventhesmallestpiecesoftheapplication.

• Codingbyinterfacesisbetter.Interfacesallowforloosecouplingandpluggability.

• Springshouldnotcompetewithgoodexistingsolutionsandshouldpromotearchitecturalchoice.

• Requiringapplicationstocheckforexceptionsservesnopurposeunlesssomerecoverycanoccurfromthedetectedexception.

• Inessence,Springprovidesaframeworkthatmanysaypromotesapplications,specificallyenterpriseapplications,thatare:

• Easierandlesscomplextodevelop.

• Easiertotestandthereforeofbetterquality.

• Moreflexibleandeasiertomaintain.

TheSpringFramework

1-8 Copyright©Intertech,Inc2014 Rev:2

Spring Architecture 

• ApplicationsbuiltontopoftheSpringFrameworkarelargelycomposedofsimpleJavaobjects.

• TheobjectsareconfiguredviaXMLor,morerecently,byannotations.

• Theframeworkcontainerprovidesmuchoftheinfrastructurefunctionality:lifecyclemanagement,transactions,etc.neededbytheseobjects.

• Springisacontainerinthatitcontainsandmanagesthelifecycleandconfigurationofapplicationobjects–calledSpringbeans.

• ThismakesSpringacontainerrunningwithinacontainer(likeanapplicationserver

orWebcontainerorJVM).

• Sidenote–theterm“bean”chosenforthePOJOsthatrunintheSpringContainerwasnotanaccident.Thetermisatake‐offofEnterpriseJavaBean.

• SpringissupposedtobealesscomplexframeworkcomparedtoframeworkslikeEJBinJavaEE.Thus,“bean”isalesscomplexEJB.

• Atitscore,theSpringFrameworkisbasedontwokeytechnologies:dependencyinjectionandaspectorientedprogramming.

• Alaterchapterisdedicatedtoeachofthesetechnologies.

• Bothpromoteloosecoupling.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-9

• DependencyInjection(DI)ishowobjects,orbeansusingtheSpringvernacular,arebroughttogetherbythecontainertoaccomplishatask.

• Dependencyinjectionisatypeofinversionofcontrol(IoC).

• Inmostapplications,anobjectisresponsibleforitsown“dependencies”orassociatedobjects.

• Forexample,acustomerserviceobjectthatneedstostorecustomerdatatothedatabasewouldseekorcreateacustomerdataaccessobjecttodotheworkforit.

• OftenthisisaccomplishedthroughnewobjectinstantiationorlookupservicesviaJNDI.

• TheDItechnique,incontrast,allowsthecontainertomanagethedependentobject’screationandassociation(inthiscasethecustomerdataaccessobject).

• Aspectorientedprogramming(AOP)isaframeworkwithintheframework.

• Itallowsdeveloperstoputcrosscuttingsystemservices(logging,auditing,security,etc.)inseparatecodeawayfromapplicationbusinesslogic.

• Theseservicesarethendeclarativelylinkedinandappliedtotherestoftheapplication.

TheSpringFramework

1-10 Copyright©Intertech,Inc2014 Rev:2

Spring Modules 

• WhilebasedonsimplePOJOorJavaBeantechnology,todaySpringisalargeandallencompassingframework.

• Springisorganizedintomanymodules(around20modulestoday)thatoffervarioustypesofassistancetothedeveloperinahostofapplicationareas.

• Thisincludespersistence,monitoring,configuration,remoting,messaging,andWebapplicationdevelopment.

• Asanapplicationdeveloper,youchoosethemodulesneededforyourapplication.

• EachmodulecontainsAPIpackages,mini‐frameworks,andintegrationsoftware(to

othernon‐Springframeworksandlibraries)toaccomplishaparticulartask.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-11

• ModulesgroupedintotheCoreContainerarethemostfundamentalpartandbaseoftheSpringFramework.

• Inparticular,theCoreandBeanmodulesprovidetheframework’sbasicdependencyinjectionfunctionalityandAPIusedbyallSpringapplications.

• Thesemodulesalsoprovidethecontainer(oftencalledtheIoCcontainer).

• TheContextmodulegivesframeworkusersaccesstobeansandotherobjectsinmannerthatissimilartoaJNDIregistry.

• TheExpressionLanguagemoduleprovidesanexpressionlanguageforqueryingandmanipulatinganobjectgraphatruntime.

• Spring’sexpressionlanguageisanextensionoftheunifiedexpressionlanguage(unifiedEL–partoftheJSP2.1specification).

• TheAspect‐OrientedProgramming(AOP)moduleprovidestheframeworkforcreatingandexecutingcrosscuttingconcernsindecoupledcode.

• Acrosscuttingconcern,liketransactions,isknownasanaspect.

• ThismoduleprovidesanAOPAlliance9(anopensourceAOP/Javaproject)compliantimplementationofAOP.

• TheAspectsmoduleprovidesintegrationtoAspectJAOP.Thisimplementationusesannotations.

• CreatedatPARC,AspectJisnowavailableasanopen‐sourceprojectviatheEclipseFoundation.

TheJDBCmoduleprovidesameanstopersistbeandataintoarelationaldatabasewithoutdirectlyusingJDBC.

• ThismoduleisaJDBCabstractionlayerasithelpstoabstractthedeveloperfromallthetediousanderrorproneworkassociatedwithJDBCcoding.

• TheJDBCmodulealsohelpstokeepdataaccesscodevendor(databasevendor)independent.

9http://aopalliance.sourceforge.net/

TheSpringFramework

1-12 Copyright©Intertech,Inc2014 Rev:2

• TheObjectRelationalMapping(ORM)modulealsoprovidesameanstopersistbeandataintoarelationaldatabase.

• However,theORMmoduledoessobyintegratingSpringtopopularobject‐relationalmappingtools/frameworkslikeHibernate,JavaPersistentAPI(JPA),etc.

• ThismoduleextendsthefunctionalityoftheJDBCmodule.

• Giventheimportanceofserviceorientedarchitecturestoday,manyapplicationsmustgetobjectinformationin/outofXMLform.

• TheObjectXMLMapping(OXM)moduleprovidesanotherabstractionlayerthatmapsobjectsto/fromXML.

• OXMsupportsJAXB,Castor,XMLBeans,JiBXandXStream.

• TheJavaMessagingService(JMS)moduleprovidesthemeansforproducingandconsumingmessages.

• Asitsnameimplies,theTransactionmodulegivestransactionsupporttotheframeworkanddataaccessinparticular.

• Spring'sWebmoduleprovidesbasicsupporttoWebdevelopmentlikefileupload,servletlisteners,andapplicationcontext.

• TheWebmodulealsooffersremotingsupport.

• IntegrationtomanypopularWebframeworkslikeStruts,JSF,andTapestryisalsofoundintheWebmodule.

• However,theWeb‐StrutsmodulesupportsintegratingwithclassicStruts(Struts1.x).

• TheWeb‐StrutsmoduleisconsidereddeprecatedasofSpring3.0andusersshouldconsidermovingtoStruts2.0andSpringMVCsolutions.

• PopulartemplateandviewgenerationtechnologieslikeVelocityandJasperReportsintegrationtoSpringarealsoavailablethroughtheWebmodule.

• TheWeb‐ServletmodulecontainsSpring’sModel‐View‐ControllerimplementationforWebapplications.

• Additionally,thePortletmodulemirrorstheWeb‐ServletmoduleandprovidesanMVCimplementationforPortal/Portletapplications.

• TheInstrumentationmodulegivescertainapplicationserversclassinstrumentationsupportandclassloaderimplementations.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-13

• TheTestmoduleallowsSpringapplicationcomponentstobeeasilyunittested.

• Specifically,thismoduleallowsapplicationstobetestedusingJUnitorTestNG.

• ItalsofacilitatesintegrationwiththeTransactionAPIsothatdatabasescanquicklyberollbackedduringtesting.

• Everyday,Springisgettingbiggerandricher.

• EachreleasehasincreasedthesizeoftheSpringFramework.

• Infact,aspreviouslymentioned,theSpringFrameworkisnolongerdistributedinasingleJARfile.

• EachmodulenowhasitsownJARfile.

• Thismany‐module,many‐JARsapproachallowsyoutoreducethe“footprint”of

Springinyourapplication.

• Pickthemodulesyouneedandkeepyourapplicationas“lightweight”aspossible.

TheSpringFramework

1-14 Copyright©Intertech,Inc2014 Rev:2

• Inadditiontothebaseframework,SpringprojectteamscreateancillarymodulesandtoolstoaddtotheSpringFramework.

• ManyofthepopularSpringProjectscanbefoundontheSpringFrameworkWebsite(http://www.springsource.com/developer/spring).

• Additionally,youcanfindSpring“extensions”here:

http://www.springsource.org/extensions/list.

• Youmightalsowanttocheckoutwww.springhub.comforadditionaladd‐onsand

resources.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-15

Obtaining Spring 

• ThefirsttaskinusingSpringistoobtaintheSpringFramework.

• ObtaintheSpringreleases(andmanyoftheSpringprojects)fromhttp://www.springsource.org/download.

• GetaSpringreleasewithorwithoutitsdependenciesandwithorwithoutitsdocumentation.

• Thedependencydownloadincludesallthird‐partydependencies,buildablesourcetrees,andsampleapplications.

• SpringusesandintegratestootherJavalibrariesandopensourceprojects(“thirdparty”code).

• WhendownloadingSpring,youcanobtainthedependentlibrariesindependentlyoryoucandownloadthemwithSpring.

• EnsuringyouhavealltheappropriateversionsofalltheappropriatedependenciesrequiredforyourversionofSpringcanbedifficult.

• Therefore,eventhoughitismuchlarger,itishighlyrecommendedthatyoudownloadSpringwithitsdependencies.

• AsofSpring3.0,aJava5environmentorgreaterisrequired.Spring3supportsJavaEE6.

TheSpringFramework

1-16 Copyright©Intertech,Inc2014 Rev:2

• IntheSpringdownload,theimportantfilesrequiredinallSpringapplicationsarethebeanandcoremoduleJARfiles.

• TheseJARscontaintheSpringcontaineranddependencyinjectionfacilitationclasses.

• WhenyouexploretheSpringdownloaddirectories,locatethedist(fordistribution)folder.

• Inthisfolder,findorg.springframework.beans‐X.RELEASE.jarandorg.springframework.core‐X.RELEASE.jar(seebelow).

• The“X”hererepresentsaversionnumber(3.0.2shownbelow).

• MaketheseJARfilesavailabletoyourJava/Springapplicationsviatheclasspath.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-17

• Spring’sonlyotherrequirementisanexternaldependencytoalogginglibrary.

• Bydefault,SpringisdependentontheJakartaCommonsLoggingAPI(JCL).

• FindthisdependentJARinthedependenciesfolderintheSpringdownload.

• Youcanturncommonsloggingofforuseadifferentloggingfacility(likeLog4J).

• Seehttp://static.springsource.org/spring/docs/3.0.x/spring‐framework‐reference/html/overview.html#d0e743fordetails.

TheSpringFramework

1-18 Copyright©Intertech,Inc2014 Rev:2

A Spring Application 

• NowthatyouknowwhatSpringis,whyitisused,andwheretogetit,youwanttoseehowtouseSpring!

• Asdiscussed,theSpringFrameworkisoftenusedinthedevelopmentofenterpriseapplications.

• However,oneofSpring’sstrengthsisthatitcanbeusedtohelpdevelopanyJavaapplication,includingsimpleJavaSEapplications.

• Intheexampleprovidedinthischapter,asimpleelectricitycalculator“bean”iscreated,configured,andusedinasimpleJavaSEapplication.

• OneofSpring’simportantphilosophiesisthatcodingtointerfacesisbetter.

• Interfacespromoteflexibility;allowingtheimplementingclasstochangeatsomepointinthefuture.

• Tothisend,thefirststepinthedevelopmentofaSpringbeanistypicallytocreateaninterfaceforthefunctionalityprovidedbytheimplementingSpringbean.

• Inthissimpleexample,theinterfacetothecalculatorbeanisprovidedbelow.

public interface Calculator { public double ohms(double volts); public double amps(double ohms); public double volts(double ohms); }

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-19

• BelowisSpringbeancodetoimplementtheCalculatorinterface.

//Ohm's Law calculator for electricity public class CalculatorImpl implements Calculator { private double watts; public void setWatts(double watts) { this.watts = watts; } public double ohms(double volts) { if (watts != 0) { return (volts * volts) / watts; } return 0; } public double amps(double ohms) { if (watts != 0) { return Math.sqrt(watts / ohms); } return 0; } public double volts(double ohms) { return Math.sqrt(watts * ohms); } }

• NoticethattheimplementationclassextendsnospecialSpringclassorinterface!

• TheimplementationisaplainordinaryJavaobject.

• InordertoconfigurethebeanandinformtheSpringcontaineraboutthecalculatorbean,thisXMLdocumentmustbeavailabletotheapplication.

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="myCalculator" class="CalculatorImpl"> <property name="watts" value="15" /> </bean> </beans>

• Forexamplepurposes,assumethattheXMLshownhereisinafilecalledspring‐beans.xml.

TheSpringFramework

1-20 Copyright©Intertech,Inc2014 Rev:2

• Finally,asimpleJavaSEapplicationcanrequestthecalculatorbeanthroughtheSpringcontainer.

import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; import static java.lang.System.out; public class Oscilloscope { public static void main(String[] args) { BeanFactory factory = new XmlBeanFactory(new FileSystemResource( "spring-beans.xml")); Calculator calc = (Calculator) factory.getBean("myCalculator"); out.println("Number of ohms for 5 volts is " + calc.ohms(5)); } }

• Theresultsofrunningthiscodearedisplayedbelow.

Number of ohms for 5 volts is 1.6666666666666667

• InthemainmethodoftheOscilloscope,theSpringcontainerisloadedandthecalculatorbeanissummoned.

• XmlBeanFactoryistheobjectthatrepresentstheSpringcontainertotheapplication.

• ThefirstlineofcodeinthemainmethodcreatesaninstanceofthecontainerandloadsitwiththeSpringbeanconfigurationfile(spring‐beans.xml).

• ThecalltogetBean()onthecontainerrequestsaninstanceoftheCalculatorImplobjectfromthecontainer.

• NotethattheCalculatorImplwatt’sfieldissetwhenitiscreatedbythecontainer(withthevalueof15).

• Congratulations!

• AsthecontainerautomaticallyprovidedtheCalculatorImplwiththevalueof15asitswattsvalue,youjustwitnessedyourfirstdependencyinjection!

• Youmightask,“wastheCalculatorinterfaceneeded?”

• InordertoshowthepowerofSpringinprovidingmoreflexibleandeasytomaintainapplications,imaginedifferentcalculatorswereneeded.

• Sayforexample,someOscilloscopesrequiredacalculatorthatcalculatesinkilojoule/secondinsteadofwatts.Onekilojoule/secondequals1000watts.

TheSpringFramework

Copyright©Intertech,Inc2014Rev:2 1-21

• Asecondelectricitycalculatorcouldeasilybeproduced.

//Ohm's Law calculator for electricity - in kilojoules public class KilojouleCalculatorImpl implements Calculator { private double kilojoules; public void setKilojoules(double kilojoules) { this.kilojoules = kilojoules; } public double ohms(double volts) { if (kilojoules != 0) { return (volts * volts) / kilojoules; } return 0; } public double amps(double ohms) { if (kilojoules != 0) { return Math.sqrt(kilojoules / ohms); } return 0; } public double volts(double ohms) { return Math.sqrt(kilojoules * ohms); } }

• Sinceanewimplementationclasswasproduced,theSpringbeanconfigurationfilewouldalsorequireachange.

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="myCalculator" class="KilojouleCalculatorImpl"> <property name="kilojoules" value="0.015" /> </bean> </beans>

• However,theuseroftheSpringbean(theOscilloscopeclass)wouldnotrequireanychangetousethenewcalculator!!!

• Ah‐loosecouplingthankstotheSpringFramework!Thatis,theOscilloscopeobjectsuseCalculatorswithoutconcernfortheactualimplementation.

Lab Exercise – Spring Intro Lab

TheSpringFramework

1-22 Copyright©Intertech,Inc2014 Rev:2

Chapter Summary                  

• TheSpringFrameworkis“anopensourceapplicationframework.”

• SpringwascreatedtoreducethecomplexityobservedinJavaenterpriseapplicationdevelopment.

• Springismeanttobea“lightweight”frameworktogetthebenefitsofJavaEEwhileminimizingthecomplexity.

• Ingeneral,Springleveragesplainordinary(orold)Javaobjects(POJOs)ormorepreciselyJavaBeanstoachieveenterprisetasks.

• However,itshouldbenotedthatSpringcanalsobeusedinnon‐enterpriseJavaapplications.

• Springislightweightinthatitreducescomplexity.

• Itisalsolightweightinitssizeandcodeimpact.

• Springalsoworkshardtobenon‐intrusive.Thatis,SpringrarelyrequiresapplicationcodetoextendorimplementSpringclassesorinterfaces.

• Inessence,Springprovidesaframeworkthatpromotesenterpriseapplicationsthatare:

• Easierandlesscomplextodevelop.

• Easiertotestandthereforeofbetterquality.

• Moreflexibleandeasiertomaintain.

• ApplicationsbuiltontopoftheSpringFrameworkarelargelycomposedofsimpleJavaobjectscalledbeans.

• ThebeansareconfiguredviaXMLor,morerecently,byannotations.

• Theframeworkcontainerprovidesmuchoftheinfrastructurefunctionality:lifecyclemanagement,transactions,etc.neededbytheseobjects.

• Springcanbeobtainedfromhttp://www.springsource.org/download.

Copyright©Intertech,Inc2014Rev:4 1-1

Chapter 1  

SpringWebMVCIntroduction

Objectives:

UnderstandthecomplexityofWebapplicationdevelopmentandtheneedforaframework.

LearnwhatanMVCframeworkisandhowithelpsinthedevelopmentofapplications.

LearnaboutthemanyJavaEEMVCframeworks.

UnderstandtheimpactofSpring3totheWebMVCframework.

SpringWebMVCIntroduction

1‐2 Copyright©Intertech,Inc2014 Rev:4

ChapterOverview

IftheacronymMVCmeansnothingtoyou,thisintroductorychapterattemptstoclarifywhatMVCisallaboutandwhyorganizationsoftenadopttheMVCpatternwhendevelopingWebapplications.Moreprecisely,youexaminewhyorganizationsoftenadoptanMVCframeworkwhendevelopingWebapplications.

SpringWebMVCIntroduction

Copyright©Intertech,Inc2014Rev:4 1‐3

Java Web Applications 

• BuildingWebapplicationscanbeadifficulttask.

• AllinformationexchangedinHTMLoverHTTPisintheformofStrings.

• Thisformofdataexchangerequiresalotofdataconversionandissubjecttomanydatavalidationissues.

• TheserversideisusuallyrequiredtohaveextensiveknowledgeoftheclientsideUIinordertoextractdatafromthekey/valuepairsintherequestobject.

• HTTPisgenerallystateless,sotrackingauser’sactionsandinformationovermanyrequestsandresponsesrequiresstatemanagementactivities–usuallyviasession.

• WorkingwithHTMLcanbetedious,errorprone,anddifficulttocreategraphicallypleasinguserinterfaces.

• Websitenavigationandworkflowcanbedifficulttoorchestrateandevenhardertochange/adapttonewbusinessneeds.

• Mostsoftwareengineerssoonlearnthatitisimportanttodivideanyapplication(Weborotherwise)intoseparatelayers.

• Specifically,mostsignificantapplicationsaredividedintopresentation(oruserinterface),businessordomainlogic,anddataaccesslayers.

• Whenimplementedcorrectly,applicationsdividedinthismanneralloweachlayertobesignificantlymodified,orevenreplaced,withoutaffectingtheothers.

• Forexample,thedataaccesslayercanbechangedtogetdatafromadifferentsourcewithoutcausingthedomainlogicorUItochange.

• Loosecouplingbetweenthelayersprovidesforflexibilityandeaseofmaintenance.

SpringWebMVCIntroduction

1‐4 Copyright©Intertech,Inc2014 Rev:4

• TheModelViewController(MVC)patterncarriesthisideafurther.

• InMVCapplications,thepresentationlayerisfurtherdividedintoviewandcontrollerlayers.

• InanMVCapplication,thebusinessordomainlogicanddataaccesslayersareseencollectivelyasthemodel.

• Themodelencapsulatestherawdataandbusinesslogicthatoperateonthatdata.Themodelshouldalsonotifyobserveswhenithaschanged.

• Thecontrollerrespondstoevents,typicallyuseractions,andinstructsthemodelandtheviewtoperformactionsbasedontheevents.

• Thecontrollermayinvokechangesonthemodel.

• Theviewrendersinformationsuppliedbythemodelinaformsuitableforuserinteraction.Multipleviewsmayexistfordifferentdisplaysofthesamemodel.

• Theviewmayalsoservetocaptureeventstosendtothecontroller.

SpringWebMVCIntroduction

Copyright©Intertech,Inc2014Rev:4 1‐5

• IntheJavaEEarena,severalframeworksprovideassistancetodevelopersinimplementingMVCWebapplications.

• Whileservlets,JSPs,JSPtaglibraries,andJavaBeansprovidetherawingredientsfordevelopingMVCWebapplications,thereisstillalotofworktoaccomplish.

• Aframeworkprovidesalotoftheapplicationinfrastructure,or“plumbing”,allowingdeveloperstoconcentrateonbusinesscode,notinfrastructurecode.

• Forexample,aframeworkoftenprovidesinfrastructurecodeforhandlingdatavalidation.

• AframeworkalsohelpstoformalizetheuseoftheJavaWebtechnologiesmakingtheapplicationeasiertodevelopandmaintain.

• Forinstance,frameworksoftendictatehowservlets,intheroleofcontroller,reacttoeventsandcallonthenextviewtobedisplayed.

• Mostframeworksalsoprovidecommonout‐of‐the‐boxservicesandfunctionalitythatWebdevelopersoftenneed.

• Theseinclude,butarenotlimitedto,dataconversion,internationalization/localization,populatingformfields,etc.

• ThetablebelowlistssomeofthemorepopularMVCWebframeworksinJava.

MVCFrameworks

Spring MVC

Struts

JavaServer Faces

Cocoon

Tapestry

SpringWebMVCIntroduction

1‐6 Copyright©Intertech,Inc2014 Rev:4

• Inthisclass,youexploretheSpringMVCFramework.

• TheSpringWebMVCframeworkisbasedonservlets,JSPs,taglibraries,andJavaBeans–justlikemanyofitscompetitors.

• Asyoumightimagine,SpringWebMVCalsoreliesonthepoweroftheSpringcontainerandotherSpringAPIs.

• IntheSpringMVCworld,therearemanycomponentstoorchestrateeachrequest/responsetotheuser.

• Eachcomponenthasaspecifictask.

• Whilethismightseemtoaddcomplexity,itallowsformaximumflexibilityandcustomization.

• Eachcomponentcanbeconfiguredorre‐engineeredforspecificapplicationneeds.

• AsyouhaveprobablycometoexpectwithSpring,itcanintegratewith“bestofbreed”solutionsinallaspectsofapplicationdevelopment.

• IntheWebMVCworld,Springholdstothispremise.

• Whilenotcoveredinthisclass,theSpringFrameworkintegratestoseveralpopularMVCframeworkslikeStrutsandJSF.

• Inaddition,SpringMVCcanbeusedwithseveralpopulartemplatingandMVCancillarytechnologieslikeVelocity,FreeMarker,andTiles.

• ASpringMVCPortletFrameworkisalsoprovidedforthosethatneedtobuildWebportals.

• TheSpringMVCPortletFrameworkmimicsthearchitectureandstyleoftheSpringMVCFramework.

SpringWebMVCIntroduction

Copyright©Intertech,Inc2014Rev:4 1‐7

Spring 3 and Web MVC 

• IfyouhaveusedtheSpringWebMVCframeworkinpast(priortoSpring3),recognizethatSpring3broughtmajorchangestotheWebMVCframework.

• Inmanyways,theSpring3WebMVCframeworkissimplerthantheoldWebMVCframework.

• RodJohnson,thecreatoroftheSpringFramework,feelsthenewframeworkismuchbetterthantheoldversion.

We view the Annotation based Spring MVC usage model that we introduced in Spring 2.5 is being a far superior replacement.1

• Unfortunately,thenewframeworkisquitedifferentandrequires,inmostcases,arewriteofapplicationsusingtheoldframework.

• Infact,manyoftheSpring1.xand2.xWebMVCcomponentsaredeprecatedinSpring3.

• ThenewSpring3WebMVCframeworkisbasedonbuildingPlainOld(orOrdinary)JavaObjectstocreateWebapplications.

• TheoldframeworkrequiredimplementingorextendingWebMVCspecificinterfacesorclasses–violatingtheloosecouplingphilosophyofSpring.

• ThenewSpring3WebMVCframeworktypicallyrequiresfewercomponentsandlesscoding‐deferringmoreoftheworktotheframework.

1http://www.infoq.com/interviews/Spring‐3.0‐Rod‐Johnson

SpringWebMVCIntroduction

1‐8 Copyright©Intertech,Inc2014 Rev:4

• ThenewSpring3WebMVCframeworkisalsobasedheavilyonannotationsforoperationandconfiguration.

• ThisrequiresdeveloperstohaveafirmgrasponautowiringandSpringannotationconfiguration.

• Inordertoeitherrefreshyourmemoryorgetyouuptospeed,bothautowiringand

annotationsarecoveredinsomedetailinthefirstchaptersofclass.

• Infact,anumberofnewannotationswereaddedtoSpring3.

• SoevenifyouarefamiliarwithSpringandannotations,theintroductorychapterswilllikelyintroduceyoutomanynewannotations.

• Youcanandlikelywillusetheseannotationsinmanyplacesinyourapplications–toincludeyourSpringWebMVCcomponents.

• UnderthenewWebMVCarchitecture,onecanarguethatthelinesbetweenwhatisa“normal”Springcomponentandwhatisa“WebMVC”componentareblurred.

• Someotherframeworkadditions/changestoSpring3arelikelytobeusedbyallWebMVCapplications.

• Thenewtypeconversionsystemandformattingsystemsfallintothiscategory.

• However,strictlyspeaking,theseadditionsarenotpartoftheWebMVCframework.

• Infact,theseadditionalcanbeusedoutsideofWebMVCapplications/environments.

• Therefore,inadditiontoWebMVC,youalsolearnsomeofthesenewfeaturesprovidedbySpring.

LabExercise–thereisnolabforthischapter

SpringWebMVCIntroduction

Copyright©Intertech,Inc2014Rev:4 1‐9

Chapter Summary 

• BuildingWebapplicationscanbeadifficulttask.

• Mostsoftwareengineerssoonlearnthatitisimportanttodivideanyapplication(Weborotherwise)intoseparatelayers.

• TheModelViewController(MVC)patterncarriesthisideafurther.

• InMVCapplications,thepresentationlayerisfurtherdividedintoviewandcontrollerlayers.

• IntheJavaEEarena,severalframeworksassistdevelopersinimplementingMVCWebapplications.

• IntheSpringMVCworld,therearemanycomponentstoorchestrateeachrequest/responsetotheuser.

• Eachcomponenthasaspecifictask.Whilethismightseemtoaddcomplexity,itallowsformaximumflexibilityandcustomization.

• IfyouhaveusedtheSpringWebMVCframeworkinpast(priortoSpring3),recognizethatSpring3broughtmajorchangestotheWebMVCframework.

• Inmanyways,theSpring3WebMVCframeworkissimplerthantheoldWebMVCframework.

• Unfortunately,thenewframeworkisquitedifferentandrequires,inmostcases,arewriteofapplicationsusingtheoldframework.

Copyright©Intertech,Inc.2014Rev:2 1-1

Chapter 1  

IntroducingSpringWebMVC

Objectives:

UnderstandthecomplexityofWebapplicationdevelopmentandtheneedforaframework.

LearnwhataWebMVCframeworkisandhowithelpsinthedevelopmentofapplications.

LearnaboutthemanyJavaEEWebMVCframeworks.

ExploreSpring’sWebMVCFramework.

SeehowtosetupandconfigureanapplicationtousetheSpringWebMVCFramework.

ExaminethecomponentsofaSpringWebMVCapplication.

SeeasimpleSpringWebMVCexampleapplicationtounderstandthepurposeoftheSpringWebMVCcomponents.

IntroducingSpringWebMVC

1-2 Copyright©Intertech,Inc.2014 Rev:2

ChapterOverview

TheSpringWebMVCmoduleprovidesaWebMVCapplicationframework.LikeotherJavaMVCframeworks,itprovidesstatemanagement,workflow,validation,etc.Inaddition,likeotherWebMVCframeworks,itisbasedprimarilyonexistingservlet,JSPandJSPtagtechnology.

Unlikeotherframeworks,SpringusesJavaBeansandDItocreateandassembletheWebMVCenvironment.TheSpringWebMVCFrameworkismodular,sovariouscomponentswithintheframeworkcanbeeasilyreplaced.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-3

Java Web Applications 

• BuildingWebapplicationscanbeadifficulttask.

• AllinformationexchangedinHTMLoverHTTPisintheformofStrings.

• Thisformofdataexchangerequiresalotofdataconversionandissubjecttomanydatavalidationissues.

• TheserversideisusuallyrequiredtohaveextensiveknowledgeoftheclientsideUIinordertoextractdatafromthekey/valuepairsintherequestobject.

• HTTPisgenerallystateless,sotrackingauser’sactionsandinformationovermanyrequestsandresponsesrequiresstatemanagementactivities–usuallyviasession.

• WorkingwithHTMLcanbetediousanderror‐prone,anditcanbedifficulttocreategraphicallypleasinguserinterfaces.

• Websitenavigationandworkflowcanbedifficulttoorchestrateandevenhardertochange/adapttonewbusinessneeds.

• Mostsoftwareengineerssoonlearnthatitisimportanttodivideanyapplication(Weborotherwise)intoseparatelayers.

• Specifically,mostsignificantapplicationsaredividedintopresentation(oruserinterface),businessordomainlogic,anddataaccesslayers.

• Whenimplementedcorrectly,applicationsdividedinthismanneralloweachlayertobesignificantlymodified,orevenreplaced,withoutaffectingtheothers.

• Forexample,thedataaccesslayercanbechangedtogetdatafromadifferentsourcewithoutcausingthedomainlogicorUItochange.

• Loosecouplingbetweenthelayersprovidesforflexibilityandeaseofmaintenance.

IntroducingSpringWebMVC

1-4 Copyright©Intertech,Inc.2014 Rev:2

• TheModelViewController(MVC)patterncarriesthisideafurther.

• InMVCapplications,thepresentationlayerisfurtherdividedintoviewandcontrollerlayers.

• InanMVCapplication,thebusinessordomainlogicanddataaccesslayersareseencollectivelyasthemodel.

• Themodelencapsulatestherawdataandbusinesslogicthatoperateonthatdata.Themodelshouldalsonotifyobserverswhenithaschanged.

• Thecontrollerrespondstoevents,typicallyuseractions,andinstructsthemodelandtheviewtoperformactionsbasedontheevents.

• Thecontrollermayinvokechangesonthemodel.

• Theviewrendersinformationsuppliedbythemodelinaformsuitableforuserinteraction.Multipleviewsmayexistfordifferentdisplaysofthesamemodel.

• Theviewmayalsoservetocaptureeventstosendtothecontroller.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-5

• IntheJavaEEarena,severalframeworksprovideassistancetodevelopersinimplementingWebMVCapplications.

• Whileservlets,JSPs,JSPtaglibraries,andJavaBeansprovidetherawingredientsfordevelopingWebMVCapplications,thereisstillalotofworktodo.

• Aframeworkprovidesalotoftheapplicationinfrastructure,or“plumbing,”allowingdeveloperstoconcentrateonbusinesscode,notinfrastructurecode.

• Forexample,aframeworkoftenprovidesinfrastructurecodeforhandlingdatavalidation.

• AframeworkalsohelpstoformalizetheuseoftheJavaWebtechnologies,makingtheapplicationeasiertodevelopandmaintain.

• Forinstance,frameworksoftendictatehowservlets,actingascontrollers,reacttoeventsandcallonthenextviewtobedisplayed.

• Mostframeworksalsoprovidecommonout‐of‐the‐boxservicesandfunctionalitythatWebdevelopersoftenneed.

• Theseinclude,butarenotlimitedto:dataconversion,internationalization/localization,populatingformfields,etc.

• ThetablebelowlistssomeofthemorepopularWebMVCframeworksinJava.

WebMVCFrameworks

Spring Web MVC

Struts

JavaServer Faces

Cocoon

Tapestry

IntroducingSpringWebMVC

1-6 Copyright©Intertech,Inc.2014 Rev:2

• Inthisclass,youwillexploretheSpringWebMVCFramework.

• However,asyouhaveprobablycometoexpect,Springcanintegratewith“bestofbreed”solutionsinallaspectsofapplicationdevelopment.

• IntheWebMVCworld,Springholdstothispremise.

• Whilenotcoveredinthisclass,theSpringFrameworkintegratestoseveralpopularMVCframeworkslikeStruts2andJSF.

• Inaddition,SpringWebMVCcanbeusedwithseveralpopulartemplatingandancillarytechnologieslikeVelocity,FreeMarker,andTiles.

• ASpringWebMVCPortletFrameworkisalsoprovidedforthosewhoneedtobuildWebportals.

• TheSpringWebMVCPortletFrameworkmimicsthearchitectureandstyleoftheSpringWebMVCFramework.

• InadditiontothemodulesanddependenciesusedbyotherpartsofyourSpringapplication,youneedtheSpringWebandServletmodules.

• Specifically,youneedtoaddthespring‐webmvcdependencytoyourMavenpom.xmlfile.

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.0.RELEASE</version> </dependency>

• Thespring‐webmvcisdependentonthespring‐webandspring‐context(includingspring‐beansandspring‐core)modules.

• TheseareautomaticallyincludedinyourSpringWebMVCprojectbyincludingspring‐webmvcinyourpom.xml.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-7

Spring Web MVC Architecture 

• IntheSpringWebMVCworld,therearemanycomponentstoorchestrateeachrequest/responsetotheuser.

• Eachcomponenthasaspecifictask.

• Whilethismightseemtoaddcomplexity,itallowsformaximumflexibilityandcustomization.

• Eachcomponentcanbeconfiguredorre‐engineeredforspecificapplicationneeds.

• InaSpringWebMVCworld,justasinallWebenvironments,Webapplicationsareaboutprocessingaclient’s(typicallyabrowser’s)Webrequest.

• WebrequestscarryinformationaboutwhattheuserwantsintheformofarequestURL.

• TheURLoftherequestisusedbytheISPstoeventuallygettherequesttotheWebcontainercontainingyourSpringapplication.

IntroducingSpringWebMVC

1-8 Copyright©Intertech,Inc.2014 Rev:2

• Oncethecontainerhastherequest,itchannelstherequesttotheSpringWebMVCFramework‐providedDispatcherServlet.(See#1inthediagrambelow.)

• ThereisatleastoneDispatcherServletinaSpringWebMVCapplicationtohandle

requests.

• TheDispatcherServlet’sjobistomarshalrequeststoothercomponentsandtoorchestratearesponsebacktotheclient.

• Spring’sDispatcherServletisthe“frontcontroller”oftheMVCenvironment.AservletservesasthefrontcontrollerinmanyWebMVCframeworks.

• TheDispatcherServletissynonymouswiththeActionServletorFacesServletinStrutsandJSFenvironments.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-9

• ThetaskofactuallyprocessingtherequestandcallingonvariousbusinesslogiccomponentsisthejobofacontrollercomponentinSpringWebMVC.

• Thecontrolleristhereal“C”inthisMVCimplementation.

• InmostWebapplications,therearegoingtobeseveralcontrollercomponents.Eachisdedicatedtospecificrequestsandactionsbytheuser.

• Controllersaredesignatedassuchwith@Controllerstereotypecomponentannotations.

• TheDispatcherServlet’sfirstjobistogettherightrequeststotherightcontroller.

• TheDispatcherServletdoesnotinnatelyhaveinformationaboutwhichcontrollertocallforarequest.

• AnnotationsonthecontrollerinformtheSpringWebMVCenvironmentaboutwhichrequestsaremappedtothecontroller.

• Specifically,the@RequestMappingannotationinformsSpringhowtomapURLrequeststoacontrollerorevenaspecificmethodonthecontroller.

IntroducingSpringWebMVC

1-10 Copyright©Intertech,Inc.2014 Rev:2

• Basedonthemappingannotations,theDispatcherServletcallsontheappropriatecontrollercomponent.(See#2inthediagram.)

• Thecontrollerisresponsiblefortakingtheuser’srequestdata,processingit,and

providingtheDispatcherServletwithdataandtheviewtoshowtheusernext.

• Inmostcases,thecontrollermerelycallstootherbusinessand/orbackendcomponents.(See#3inthediagramabove.)

• AsaWebdeveloper,youmustwritethecontroller.

• ControllersareakintoStrut’sActionclassesorJSF’smanagedbeans.

• Controllercomponentsarenotthread‐safeandmayreacttomultiplerequestscomingfromtheDispatcherServlet.

• Therefore,goodcontrollersquicklycalltootherservicecomponentsandgetreadyforthenextrequest.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-11

• Whenitsjobiscomplete,thecontrollerinformstheDispatcherServletwhichviewtoshownextandwhatdatashouldgoonthatdisplay.

• Typically,thenextviewiscomprisedofHTMLcreatedfromaJSP.

• However,thenextviewmaybeaPDFdocument,Excelspreadsheetorotherformatofresponse.

• Thedatatobedisplayedismodelinformationobtainedviathebackendservices.

• Modelinformationcanbemanythings,dependingontheview.

• Forexample,itmightbeacollectionoforderobjectstobeshowninthedisplayofopenordersorthecustomerobjectofthecustomerrecordtobeedited.

• Itmaysimplybeapieceoftexttodisplaytotheuser.

IntroducingSpringWebMVC

1-12 Copyright©Intertech,Inc.2014 Rev:2

• SpringWebMVCprovidesaspecialobjecttocommunicateboththenextviewandmodeldatatotheDispatcherServlet.

• Itiscalled,appropriately,theModelAndViewobject.(See#4inthediagram.)

• The“view”halfoftheModelAndViewobjectisaStringthatisthelogicalnameofthe

nextviewtobedisplayed.

• Theviewnameisnottheactualorphysicalnameofthenextview.(Forexample,itisnotthenameofaJSP.)

• Theviewnameasalogicalname(notphysicalname)allowsthelogicalnametoberesolveddynamically.

• The“model”halfoftheModelAndViewisakey‐valuepair.Themodelinformationisgivenanameorkeybywhichitcanbereferredtointheview.

• Theactualdataormodelinformationtobeusedinthenextviewisthevaluepartofthekey‐valuepairinthe“model”half.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-13

• TheModelAndViewobjectthattheDispatcherServletreceivesfromthecontrollercontainsthelogicalnameofthenextview.

• TheDispatcherServletdoesnotknowhowtoresolvethisinformationintoaphysicalviewtobeobtainedanddisplayedbacktotheuser.

• ItturnstoaViewResolvercomponenttoresolvethelogicalviewnameintheModelAndViewintoaphysicalviewname.(See#5inthediagram.)

• TheViewResolverisacomponentthatisagainprovidedbySpring.

• Infact,thereareseveraltypesofviewresolversfromwhichtochoose.

• DevelopersdonothavetowritetheViewResolver,buttheyoftenhavetoconfiguretheViewResolverintheSpringconfigurationfile.

• TheconfigurationinformationhelpstheViewResolverdeterminethephysicalviewname.

• TheViewResolver(anditsconfiguration)allowsthephysicalviewtoberesolveddynamically.

• Thisallowsthecontrollercodeandlogicalnameitreturnstoremainstaticwhileallowingthedisplayworkflowtochangemoredynamically.

• Forexample,the“displayOrders”logicalnamemaytodayresolvetothedisplayorders.jsp,buttomorrowresolvetotheadvertisement.jsp.

IntroducingSpringWebMVC

1-14 Copyright©Intertech,Inc.2014 Rev:2

• Lastly,withthephysicalviewnameandmodelinformationinhand,theDispatcherServletcancalltorendertheviewandrespondtotheuser(#6).

• Intheviewlayer,Springcallsonviewbeans.Viewbeansknowhowtocreatea

response.Sometimestheviewbeansneedtheassistanceofaviewtemplate.

• Templatesaredocuments.Thesedocumentsusesometypeofmarkuplanguagetoprovideinstructionsonhow/whattodisplay.

• JSPsareconsideredtemplatedviews.However,thereareanumberoftemplatetechnologies.

• VelocityandFreeMarkeraretwoothertemplateviewtechnologies.

• Insomecases,viewbeansmayrenderwithouttheaidofatemplate.Theseviewbeanshelprender“non‐templated”views.

• TheviewbeanmaycreateandrespondwithaMIMEtypelikeplaintext,anExcelspreadsheet,PDFdocument,etc.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-15

• WhenJSPtemplatesareusedtoprovidetheview,aspecialsetofJSPtagscanhelpcreatetheview.

• SpringWebMVChasacoupleofJSPtaglibrariestoassistdeveloperscreatetemplateviews.

• Inparticular,thesetagscanbeusedtobindmodeldatatoHTMLformviewsandviceversa(notunlikewhatStrutsandJSFoffer).

• Ofcourse,theterm“lastly”meansthelaststepinanysingleHTTPrequest/responsecycleofaWebapplication.

• Oncetheviewisshippedbackanddisplayedonthebrowser,thewholeprocessstartsagainwiththenextuseractionandrequestoftheWebsite.

• Toaccomplishsomethingassimpleasonlineshoppingandcheckoutmightrequiretensorhundredsofsuchrequests/responses.

IntroducingSpringWebMVC

1-16 Copyright©Intertech,Inc.2014 Rev:2

Spring Web MVC Hello World 

• TobeginyourstudyofSpringWebMVC,asimpleandubiquitousHelloWorldapplicationisusedtodemonstratethenecessarycomponents.

• ItshouldgiveyouanappreciationoftheSpringWebMVCcomponentsandhowtheyworktogethertomanageWebapplicationrequests/responses.

• Inthisexample,asimpleJSP(index.jsp)requestsauser’sname.

• Afterenteringhisorhernameandselecting“OK,”(causingasubmitrequestofthe

HTMLform),theWebapplicationrepliestotheuserwithanappropriategreeting.

• Theindex.jsppagethatcapturestheuser’sinputandsendstheinitialrequestintotheSpringWebMVCapplicationisshownbelow.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Greeting Request</title> </head> <body> <form action="greeting.request" method="post"> Your name please:<input type="text" name="name" /><br /> <input type="submit" value="OK" /><br/> </form> </body> </html>

• Thereisn’tanythingparticularlySpringWebMVC‐specialhere.Infact,itisjustagoodold‐fashionedHTMLform.

• Takeparticularnote,however,thattheform’sactionis“greeting.request”.

• Thismeansthatwhentheuserfillsouttheformandselectssubmit,therequestURLsentintotheserveris“http://server:port/appcontext/greeting.request”.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-17

• Who/whatreceivestherequest?TheSpringWebMVCDispatcherServletmustbeconfiguredtogetthisrequest.

• TheDispatcherServletisprovidedbytheSpringWebMVCFramework.Itmustbeconfiguredasanyservletis.

• Thatis,theDispatcherServletmustbeconfiguredanditsrequestmappingsdefinedintheweb.xmlfile.

• Ataminimum,<servlet>and<servlet‐mapping>elementsmustbeaddedtotheweb.xmlfile(typicallylocatedintheWebContent/WEB‐INFfolder).

<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.request</url-pattern> </servlet-mapping>

IntroducingSpringWebMVC

1-18 Copyright©Intertech,Inc.2014 Rev:2

• InServlet3.0(orbetterenvironments),theweb.xmlfileisnolongerrequired.

• UndertheServlet3.0API,servletregistrationandmappingsareaccomplishedbyannotations.

• Therefore,asofSpring3.1,developerscanconfiguretheDispatcherServletprogrammaticallyandavoidhavingtoaddanyelementstoweb.xml.

• DevelopersneedtoimplementtheWebApplicationInitializerinterfaceprovidedbySpringWebMVC.

• TheimplementationofthisinterfaceregisterstheDispatcherServletwiththeWebcontainerandspecifiesitsmapping.

• Theimplementationbelowisequivalenttotheweb.xmladditionsinthesectionabove.

public class WebMVCApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) { ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet()); registration.setLoadOnStartup(1); registration.addMapping("*.request"); } }

• WhenacustomWebApplicationContextisrequired,itisrecommendedthattheSpringcontainerbecreatedintheinitializerandattachedtotheWebcontainer.

public class WebMVCApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext)); registration.setLoadOnStartup(1); registration.addMapping("*.request"); } }

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-19

• Thenamechosenfortheservletisarbitrary.However,itcanimpactthenameoftheSpringconfigurationfilethatisusedbydefault.

• Bydefault,whentheDispatcherServletisloaded,aSpringapplicationcontextcontainerisstarted.

• Moreprecisely,eachDispatcherServlethasitsownXmlWebApplicationContextcontainer.

• XmlWebApplicationContextisanimplementationoftheWebApplicationContextinterface.

• TheWebApplicationContextinterfaceisanextensionofApplicationContext.

• AWebApplicationContexthassomeextrafeaturesnecessaryforwebapplications(suchasresolvingthemes).

• Bydefault,theWebApplicationContextisloadedwithbeansdefinedinanXMLfilecalled[servlet‐name]‐servlet.xmlfoundintheWebContent/WEB‐INFfolder.

• Inthisexample,thatwouldmeanallSpringbeansaredefinedina/WebContent/WEB‐INF/dispatcher‐servlet.xmlfile.

• Later,youwilllearnhowtomodifythisdefaultconfiguration.

• ItshouldbenotedthattheWebApplicationContextcontainerisboundintheServletContext.

• ThisallowstheWebApplicationContext(thebeanfactory)tobeaccessedanywhereintheWebapplication.

• WhileavailablethroughtheServletContext,aspecialSpringutilityclass(RequestContextUtils)allowsthebeanfactorytobeeasilyretrievedfromanywhere.

//use any HttpServletRequest object to retrieve the bean factory. WebApplicationContext factory = RequestContextUtils.getWebApplicationContext(request); Object o = factory.getBean("greetingService");

IntroducingSpringWebMVC

1-20 Copyright©Intertech,Inc.2014 Rev:2

• Theurl‐patternisalsoarbitrary,however,*.requestissomewhatcommoninSpringWebMVCdevelopmentcircles.

• Theurl‐patternisusedbytheWebcontainertorouteallmatchingrequestURLtraffictotheSpringWebMVCDispatcherServlet.

• DeveloperswhowanttoreallyobfuscatetheMVCenginethatrunstheapplicationhavechosen*.htmastheurl‐pattern.

• WithrequestsnowroutedtotheDispatcherServlet,theDispatcherServletlookstoroutetraffictocontrollers.

• Controllersaredesignatedwith@Controllerstereotypeannotations.

• Recallthatyoumustincludeacomponent‐scanelement(shownbelow)intheSpringconfigurationfileforSpringtoautomaticallydetectthestereotypecomponents.

<context:component-scan base-package="com.intertech"/>

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-21

• TheDispatcherServletscansknownControllerstereotypesfor@RequestMappingannotations.

• The@RequestMappingannotationsmaprequestURLstothecontrollerand/orcontrollermethod.

• Youwilllearnmoreaboutcontrollersandmappingsinthenextchapter.

• BeforeSpring2.5,anMVCcomponentcalledtheHandlerMappingwasusedinplaceof@RequestMappingannotationstomaprequeststocontrollers.

• Itcanstillbeusedtoday,butannotationsarepreferred.

• Infact,asofSpring3.1,theDispatcherServletworksunderthecoverswithaRequestMappingHandlerMappingobject.

• Itisactuallythedefault‐annotation‐basedhandlermappingobjectthatlooksfor@RequestMappingannotationsanddetermineswhichcontrollertocall.

IntroducingSpringWebMVC

1-22 Copyright©Intertech,Inc.2014 Rev:2

• HereisaverysimplecontrollerfortheHelloWorldMVCapplication.

import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.intertech.service.HelloService; @Controller public class HelloWorldController { @Autowired private HelloService service; public void setService(HelloService service) { this.service = service; } @RequestMapping("/greeting.request") protected ModelAndView sayHello(HttpServletRequest request) { return new ModelAndView("greet", "message", service.getGreetingMessage(request.getParameter("name"))); } }

• Again,the@Controllerannotationdesignatesthisclassasacontroller,whichtheDispatcherServletdetects.

• The@RequestMappingtellstheDispatcherServletwhatrequeststoroutetothesayHellomethodonthecontroller.

• MethodslikesayHelloarecalledhandlermethodsinSpringWebMVC.They“handle”incomingrequests.

• Inthiscase,whenaURLof“greeting.request”comesin,itisroutedtothesayHello()methodofaninstanceoftheHelloWorldController.

• Noticethe“/greeting.request”parametermatchestherequestURLcomingfromthesubmitrequestontheindex.jsppage!

• YoumayalsonotethatthesayHello()methodispassedthestandardHttpServletRequestobject.

• Therequestobjectisusedheretoretrievetheuser’sname(suppliedviatheHTMLform)throughacalltorequest.getParameter().

• Springdetectstheparameterinthehandlermethodandautomaticallyprovidestheneededobject–inthiscasetherequestobject.

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-23

• Becausethecontrollerstartsthebusinessmodelwork,itisoftendependency‐injectedwithservice,DAO,andotherbeansthatassistinrequestprocessing.

• Inthisexample,thecontrollerisdependency‐injectedwithaHelloServicebean.

• BelowistheHelloServicebeanimplementation.

package com.intertech.service; import org.springframework.stereotype.Service; @Service public class HelloService { private String greetingMessage = "Greetings and Salutaions"; public String getGreetingMessage(String name) { return greetingMessage + " " + name; } }

• Notethe@Servicestereotypeannotationinthecodeabove.

• Asistypical,controllerobjectsoftencommunicatewithserviceroleobjectstogetbusinesslogicperformed.

IntroducingSpringWebMVC

1-24 Copyright©Intertech,Inc.2014 Rev:2

• NowyouhaveseenhowtrafficisroutedintobusinesslogicwiththehelpofSpringWebMVCcomponents(steps#1‐3).

• What’snext?

• Howistheresponseformulatedandrelayedbacktotheuser?

• Howismodeldatashownonthatresponse?

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-25

• Inthisexample,thecontroller’srequesthandlingmethod(sayHello)returnsaModelAndViewobject.

@RequestMapping("/greeting.request") protected ModelAndView sayHello(HttpServletRequest request) { return new ModelAndView("greet", "message", service.getGreetingMessage(request.getParameter("name"))); }

• ThereareseveralModelAndViewconstructors.However,acommonconstructorthatisusedinthisexampletakesasitsparametersthefollowing:

# ModelAndViewconstructorparameters

1 Logical view name

2 Model name or key

3 Model value

• The“view”halfoftheModelAndViewobjectisaStringthatisthelogicalnameofthenextviewtobedisplayed.

• Inthiscase,thelogicalnameofthenextviewis“greet.”

• The“model”halfoftheModelAndViewisamapofkey‐valuepairsoftheactualdataormodelinformationtobeusedinthenextview.

• Inthisexamplecase,thedatatobedisplayedincludesonlyonekey‐valuepair.

• Thekeytothekey/valuepairis"message."

• Thevaluetothe“message”keyiswhateverisreturnedfromthecalltoservice.getGreetingMessage(request.getParameter("name").

IntroducingSpringWebMVC

1-26 Copyright©Intertech,Inc.2014 Rev:2

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-27

• So,theControllerreturnsaModelAndViewobjecttotheDispatcherServlet.Again,theservletmustturntoanassistingcomponentfordirection.

• AViewResolverassiststheDispatcherServletinfiguringoutwhichviewtoshowtotheusernextbasedonthe“view”informationintheModelAndViewobject.

• Viewresolversarealsobeans.Thesebeansmustimplementtheorg.springframework.web.servlet.ViewResolverinterface.

• SpringcomeswithseveralViewResolverimplementations.Thisallowsyoutosimplyuseandconfigureaviewresolverratherthanbuildyourown.

• TheInternalResourceViewResolverisusedinthisexample.

• TheInternalResourceViewResolvertakesthelogicalviewnameandattachesa“prefix”and“suffix”tocreatethephysicalviewname.

• PrefixandsuffixareprovidedinSpringconfigurationoftheInternalResourceViewResolverbean.

<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- prefix not really required here, but shown for example sake--> <property name="prefix" value="" /> <property name="suffix" value=".jsp" /> </bean>

• Inthisexample,ittakesthelogicalviewnameandadds“”tothefrontofthelogicalnameandappends“.jsp”totheendofthelogicalname.

• RecallinthecontrollerthatthelogicalnamereturnedintheModelAndViewobjectis“greet.”

• Therefore,thephysicalnamethatthisviewresolvercreatesbasedonthatlogicalnamewouldbe“greet.jsp.”

• Theprefixhereisblank(andthereforecouldbeleftout).

• IftheJSPpageswerelocatedinasubfolderofWebContent,theprefixcouldbeusedtospecifythesubfolder.

• Forexample,ifallpageswherestoredin/WebContent/hello/jsps,thentheprefixmightbeconfiguredasshownbelow.

<property name="prefix" value="/hello/jsps/" />

IntroducingSpringWebMVC

1-28 Copyright©Intertech,Inc.2014 Rev:2

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-29

• TheDispatcherServlet,withtheassistanceoftheviewresolver,nowknowsthenameoftheactualviewtodisplaynext.

• So,thelaststepinhandlingthissingleuserrequestistocreatetheviewusingtheJSPtemplateandusethemodeldatatopopulatetheviewappropriately.

• SpringusesanInternalResourceViewbeantocreateviewsfromJSPtemplates–inthiscasethegreet.jsptemplate.

• Belowisgreet.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Greeting</title> </head> <body> <H1>${message}</H1> </body> </html>

• JSPexpressionlanguagecanandoftenisusedtoextractanddisplaythemodeldatafromtheModelAndViewobjectsuppliedbythecontroller.

• Inthiscase,recallthatthecontrolleraddedthegreetingmessagestringtotheModelAndViewobjectunderthekeynameof“message.”

return new ModelAndView("greet", "message", service.getGreetingMessage(request.getParameter("name")));

• IntheJSP,expressionlanguageusesthemodelkeytoextractthisdataanddisplayitbacktotheuser.

• Inmorecomplexapplications,themodelmaybemuchmorecomplexandrequire

moresophisticatedprocessing(sometimesinvolvingJSTLorothertags)todisplay.

IntroducingSpringWebMVC

1-30 Copyright©Intertech,Inc.2014 Rev:2

Lab Exercise – MVC Intro Lab

IntroducingSpringWebMVC

Copyright©Intertech,Inc.2014Rev:2 1-31

Chapter Summary                  

• BuildingWebapplicationscanbeadifficulttask.

• Mostsoftwareengineerssoonlearnthatitisimportanttodivideanyapplication(Weborotherwise)intoseparatelayers.

• TheModelViewController(MVC)patterncarriesthisideafurther.

• InMVCapplications,thepresentationlayerisfurtherdividedintoviewandcontrollerlayers.

• IntheJavaEEarena,severalframeworksassistdevelopersinimplementingMVCWebapplications.

• IntheSpringWebMVCworld,therearemanycomponentstoorchestrateeachrequest/responsetotheuser.

• Eachcomponenthasaspecifictask.Whilethismightseemtoaddcomplexity,itallowsformaximumflexibilityandcustomization.

• TheDispatcherServlet’sjobistomarshalrequeststoothercomponentsandtoorchestratearesponsebacktotheclient.

• ThetaskofactuallyprocessingtherequestandcallingonvariousbusinesslogiccomponentsisthejobofacontrollercomponentinSpringWebMVC.

• TheDispatcherServletlookstoroutetraffictocontrollers.

• Controllersaredesignatedwith@Controllerstereotypeannotations.

• TheDispatcherServletscansknownControllerstereotypesfor@RequestMappingannotations.

• The@RequestMappingannotationsmaprequestURLstothecontrollerand/orcontrollermethod.

• Thecontrollerisresponsiblefortakingtheuser’srequestdata,processingit,andprovidingtheDispatcherServletwithdataandtheviewtoshowtheusernext.

• SpringWebMVCprovidesaspecialobjectcalledtheModelAndViewobjecttocommunicatethenextviewandmodeldatatotheDispatcherServlet.

• TheDispatcherServletturnstoaViewResolvercomponenttoresolvethelogicalviewnameintheModelAndViewintoaphysicalviewname.

• Lastly,withthephysicalviewnameandmodelinformationinhand,theDispatcherServletcanrespondtotheuserwiththenextview(anddata).

Copyright©Intertech,Inc.2014Rev:3 1-1

Chapter 1  

ObjectPersistence

Objectives:

Definepersistenceandobjectpersistence.

Understandsomeoftheissuesinpersistingobjectsinrelationaldatabases.

LookatObjectRelationalMappingandpersistentframeworksfordealingwithobjectrelationalmismatch.

SeethebenefitsofapersistenceframeworklikeHibernateinaJavaapplication.

ExaminetheoriginsofHibernate.

UnderstandthedifferencebetweenHibernateandJPA.

ExploreHibernateadd‐onprojects.

UnderstandpersistenceoptionsinJava.

ObjectPersistence

1-2 Copyright©Intertech,Inc.2014 Rev:3

ChapterOverview

Hibernatehasbeendescribedasthe“opensourcedarling”thatwonoverlargeportionsoftheJavacommunitybyprovidingJavaobjectpersistenceinmanyapplications.Whatispersistenceorobjectpersistence?Whyispersistingobjectssodifficult,andwhywouldatechnologylikeHibernatehelp?Inthischapter,thesequestionsareaddressedalongwiththegeneraltopicofobjectrelationalmapping.Throughthischapter,youseethefertilefieldthathasledtoHibernate’sascensionasaprominentframeworktotacklethisdifficultproblem.

Inaddition,youexplorethesomewhatmurkyworldofJavapersistence.TherearemanyframeworksthatprovidepersistenceinJava.Somearedefinedbyspecification,andsomearenot.Someareopen‐source,andsomesolutionsareproprietary.EvenHibernateisnowseparatedintomanyprojects.Inparticular,thischapterhelpstodelineateHibernatefromtheJavaPersistenceAPI(JPA).

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-3

Persistence 

• Whatispersistence?

• Persistenceinsoftwareengineeringisthecapabilityofacomputerprogramtostoredatain“non‐volatile”storage.

• Thisallowsdatatoexistevenwhentheprogramisnolongerrunning.

• Storageoptionsincludeafilesystem,relationaldatabase,hierarchicaldatabase,objectdatabase,etc…

• InJava,mostpersistenceisaccomplishedbystoringdatainarelationaldatabasemanagementsystem(RDBMS).

• Youusethestructuredquerylanguage(SQL)togetdatainandoutoftherelationaldatabase.

• JavaDatabaseConnectivity(JDBC)isJava’sAPItoconnecttotheRDBMSandsendSQLstatementstotheRDBMS.

ObjectPersistence

1-4 Copyright©Intertech,Inc.2014 Rev:3

Object Persistence 

• WhatisObjectPersistence?

• Dealingwithpersistenceinobject‐orientedprogramslikeJava.

• Determininghowobjectsandtheirrelationshipsarepersistedinarelationaldatabase.

• Objectpersistenceisaboutmappingobjectstate.Thatis:

• Determininghowanobject’sstate(datastoredinmembervariablesofanobject)isstoredindatabasetablecolumns.

• Dealingwiththefactthatobjectstatetypesmaynotalignwithrelationaldatabasetypes.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-5

• SomeJavaDataTypesversusSQLDataTypesareshowninthetablebelow.

JavaDataType SQLDataType

String VARCHAR

String CHARACTER

String LONGVARCHAR

BigDecimal NUMERIC

BigDecimal DECIMAL

Boolean, boolean BIT

Integer, byte TINYINT

Integer, short SMALLINT

Integer, long BIGINT

Integer, int INTEGER

Float, float REAL

Double, double FLOAT

Double, double DOUBLE PRECISION

• Objectpersistenceisalsoaboutmappingobjectrelationships.

• Thatis,determininghowassociationsbetweenobjectsarestoredasrelationaldatabasekeysorinrelationaldatabaseintersectiontables.

ObjectPersistence

1-6 Copyright©Intertech,Inc.2014 Rev:3

Object/Relational Paradigms 

• ThroughlanguageslikeSmalltalk,C++andJava,softwaredevelopershavebeensoldonthebenefitsofobject‐orientedprogramming.

• OOPisbasedonsoftwareengineeringprinciples.

• Objectsrepresentbothbehaviorandstate(ordata).

• Objectsmodelormimicthebusinessdomain(therealworld).

• Objectsareeasilytraversedthroughrelationshipgraphs(inheritance,associations).

• Objectidentityissomewhatflexible.

• However,objectsarenotgoodatdealingwithlargeamountsofinformationallatonce.

• Relationaldatabasesareprovenandentrencheddatapersistencetechnology.Theyare:

• Basedonmathematicalprinciples.

• Concernedwithdataandnotbehavior.

• Usedtostoreandretrievelargeamountsofdata.

• Notasgoodforbusinessmodeling.

• Reliantontablejoinstoassociatedata.

• Reliantonauniqueidentityindatabases.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-7

• Gettingstate(data)andassociationsfromobjectsintorelationaltablestructureandviceversarequiresalotoftediousprogramming.

• Variousstudieshaveestimatedthatbetween30‐70%1ofapplicationdevelopmentisspentonthisactivity.

• Thiscancreateproblemsinscalability,maintenance,andflexibility.

• Thisalsorequirestheobjectprogrammerandrelationaldatabaseadministratortodevelopacommonviewormodelofthedata.

• Thisisnotalwayseasytoachieve.

• Itusuallyresultsinalessthanoptimalmodelforoneorboth.

• Incongruencebetweenobjectandrelationalstructuresevenhasnames.

• Impedancemismatch

• Object/Relationalparadigmmismatch

• Object‐datadivide(ScottAmbler)

1www.dmreview.com/dmdirect/20061201/1069184‐1.html(70%figure)andJavaPersistencewithHibernatebyBauerandKing,pg.19(30%figure).

ObjectPersistence

1-8 Copyright©Intertech,Inc.2014 Rev:3

Impedance Mismatch 

• Inexaminingthedifferencesandmismatchesbetweenobjectandrelationalsystems,explorethesimpleobjectmodelbelow.

• Howshouldinstancesofobjectsinthismodelbepersisted?

• Shouldtheybestoredinanormalizedmodelforflexibilityordenormalizedforperformance?

• Howdoyoudecide?

• WhatiftheCustomer1databasetableexistedbeforetheobjectmodel?Whatwouldyouhavetodotoyourclass/objectdesign?Wouldthatbethedesiredmodel?

• Thecorrelationbetweenobjecttypestodatabasetablesisnotusuallyonetoone.

• Becauseofdatabaseperformanceneeds,objectstendtobesmallerormore“fine‐grained”thanrelationaldatabasetables.

• Havingtokeepidenticalstructureswouldlikelydestroytheobject’sabilitytomimictherealworld.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-9

• Generalization,orinheritance,providesanotheropportunityforanimpedancemismatch.

• Infact,theconceptoftheinheritancerelationshipandpolymorphismisforeigntothedatabaselexicon.

• Consideringthefollowingobjectmodel…

ObjectPersistence

1-10 Copyright©Intertech,Inc.2014 Rev:3

• Howcandatabasetablessupportthisinheritance?Databasesstrugglewithhowbesttoimplementtablesforobjectinheritance.

• Multiplestrategiesexistasrepresentedbythethreemodelsbelow.

• Optionsincludehavingrelatedtablesforeachtype,asingletableforalltypes,orasingledenormalizedtableforeachtype.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-11

• Anotherimpedanceproblemmanifestswhenconsideringpolymorphiccases.

• Forexample,acustomerobjecthasanaccount(ofeitherSavingsorCheckingtype).

• Givenacustomertable,therelationshipfromcustomertotheappropriateaccounttableisnotalwayseasilymaintainedinarelationaldatabase.

• Givenanycustomerrow,whichtabledoestheaccountidrelateto:achecking

accountorsavingsaccount?

• Acustomer’spolymorphicrelationshiptoanyaccounttypeinJavaiseasilyunderstoodandhandled.

• Thisrelationshipinadatabaseisnotsoeasilyunderstoodorhandled.

• Somedatamodelsmayactuallyprohibitorseverelyconstraintheuseofpolymorphismintheobjectmodel.

ObjectPersistence

1-12 Copyright©Intertech,Inc.2014 Rev:3

• Rowsinatableandobjectsalsomismatchontheideaofidentity.

• Arowisuniquelyidentifiedfromallotherrowsbyitsprimarykey.

• Anobject’sidentitydoesn’talwaystranslatewelltotheprimarykey.

• Infact,inJava,identityhasadifferentmeaningbasedonthechosenformof“equality.”

• Aretwoobjectsequalor“identical”underthiscondition?

accountA.equals(accountB);

• Aretwoobjectsequalor“identical”underthiscondition?

accountA == accountB

• Giventhenebulousnatureof“equal”or“identical”inJava,imaginethedifficultiesofdeterminingwhethertwoobjectsrepresentthesamedatabaseentity.

• Howshouldtwomodifiedaccountobjectscontainingthesamerelationaldatabaserowidentifieranddataupdateadatabase?

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-13

• Objectassociationspresentmultipleopportunitiesforexaminingimpedancemismatch.

• Objectsimplementassociationswithbothobjectreferencesandoperations.

• Bytheirnature,objectreferencesaredirectional.Foreachdirectionintheassociation,areferencetotheassociateobjectmustbedefined.

public class Customer { private Address address; } public class Address { private Customer occupant; }

• Therelationshipcanbebidirectionalasinthecaseabove,orunidirectional.

• Multiplicitydependsonthetypeandsubstanceoftheobjectreturnedbyanoperation.

public class Customer { private Address address; //to one private Set orders; //to many }

• Acollectionoranarrayofobjectsimpliesa“Many”relationshipinJava.However,objectreferencescanholdnullimplying“zero‐to‐many.”

• Areferencetoanothersingleobjectimpliesa“One”relationshipinJava.Again,theobjectreferencecanholdnullimplying“zero‐to‐one.”

ObjectPersistence

1-14 Copyright©Intertech,Inc.2014 Rev:3

• Inarelationaldatabase,anassociationisrepresentedviaaforeignkey.

• Foreignkeysandtablejoinsmakerelationaldatabaseassociationsdirection‐lessbynature!

//what street does Jim live on? select a.street from customer c, address a where c.name = ‘Jim’ and c.addressId = a.id //who lives on Elm select c.id, c.name from customer c, address a where a.street = ‘Elm’and c.addressId = a.id

• Multiplicityinthedatabaseusesforeignkeystoimplementone‐to‐manyrelationshipsbutusesalinktabletoestablishamany‐manyrelationship.

• Constraintsandnot‐nullrestrictionscanalsomakearelationshiprequiredor“one‐to‐one”or“one‐to‐many.”

• InJava,therequirementofarelationshipcannotbeaccomplishedintheclassdefinitionsalone.

• Requiringarelationshipcanonlybeaccomplishedprogrammatically.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-15

• Therearefundamentalwaysofdatanavigationintheobjectandrelationalworldsthathighlightonelastformofimpedancemismatch.

• Considerthefollowinggraph.

• ToknowwheretoshipthebillforanorderinaJavaprogram,thechainedmethod

callmaylooksomethinglikethefollowing:

order.getAccount().getCustomer().getAddress();

• Ofcourse,inarelationaldatabase,asingleSQLisneededtoreturnthesameinformation–evenifeachtypeabovewerestoredinaseparatetable.

• Forexample,thesingleSQLneededtoknowwheretoshipthebillforanordermaylooksomethinglikethefollowing:

select a.street, a.city, a.zip from Order o, Account acct, Customer c, Address a where o.id=acct.id and acct.id=c.id and c.id=a.id and o.id=475

• Whatcreatesproblemsisinnavigatingtheobjectgraphwhenthesupportingobjectstate(data)mustbebroughtupfromtherelationaldatabase.

• Itwouldlikelytakemanydatabaseselectstatements(oneforeachassociationtraversal)togettheaddress.

• So,intheexampleabove,anSQLquerymayneedtobeexecutedfororder.getAccount(),account.getCustomer(),etc.

• Theoverheadrequiredwhenworkingwithbothtechnologiestogetherseemstoexceedtheeaseofusingeithertechnologyalone.

ObjectPersistence

1-16 Copyright©Intertech,Inc.2014 Rev:3

Object Relational Mapping (ORM)               

• Anentirefieldofsoftwareengineeringhasgrownfromimpedancemismatch.

• ORMisthenamegiventoautomatedtechnologydevelopedtosolvethemismatchproblem.

• ORMprovidestransformationsbetweenobjectandrelationalmodels.

• Letthedatabasedothethingsitdoeswell–storeandretrievelargeamountsofdata.

• Letobjectsdothethingstheydowell–mimicthebusinessdomain.

• ORMtechnologiesprovidethetoolstobridgethetwoinordertoprovideobjectstatepersistenceinarelationaldatabase.

• Thispersistentautomationshouldbetransparenttodevelopers.

• AnORMframework(a.k.a.persistentframework)inJavameansproviding:

• AJavaAPIforperformingdatacreates,read,updateanddeleteoperationsonobjectstate(withoutdirectlyusingSQLorJDBC).

• AJavaAPItoqueryandinstantiateobjectsbasedonqueryresults.

• Ameansformappingmetadatainobjectstometadataofthedatabase.

• Amechanismforhandlingtransactionsacrosstheobject‐relationalenvironments.

• Amechanismforhandlingconcurrencyandcacheissues.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-17

Hibernate 

• HibernatewascreatedbyGavinKing.

• Itisanopensource(underGNUlicense),Javalanguage/JVM,ORMframework.

• Itwasstartedin2001,makingitoneoftheoldestandmostsuccessfulopensourceframeworksinJava.

• ItwasdevelopedtomeetneedshethoughtEJBcontainermanagedpersistent(CMP)entitybeansdidnotachieve.

• CMPdidnotscale.

• Many,includingKing,believedCMPentitybeansweretoocomplex.

• Accordingtoproductdocumentation–“Hibernate’sgoalistorelievethedeveloperfrom95%ofcommondatapersistence‐relatedprogrammingtasks.”

• In2003,JBoss,Inc.hiredtheleadHibernatedevelopers(includingKing)tofurtheritsdevelopment.

• JBossstillmanagesHibernatetoday.

• JBossspecializesinwritingandsupportingopen‐sourcemiddlewaresoftware.

• JBossisnowadivisionofRedHat,Inc.

• Hibernateisavailablefromhibernate.org.

• AllHibernateprojectdocumentationisalsoavailableonlineatthesameaddress.

• ThisclassfocusesonHibernate4.2(madeavailablein2013).

• Atthetimeofthiswriting,Hibernate5isbeingdesigned/developed,butnoreleasedatehasbeensuggested.

ObjectPersistence

1-18 Copyright©Intertech,Inc.2014 Rev:3

Why an ORM framework?  Why Hibernate? 

• Fromthedeveloper’sperspective,anORMframeworkshouldmakepersistencetransparent(ornearlytransparent).

• Therefore,theobjectdevelopershouldnothavetoknowallthespecificsaboutrelationaldatabasesandSQL.

• Thissimplifiesthedevelopmentandmaintenanceofobjectsystems.

• Hibernate,asaJavaORMframework,attemptstomakeJavaobjectpersistencetransparent(withagoalofremoving95%ofrelatedprogrammingtasks).

• While95%isambitious,theHibernateWebsitereportsthatmostseea30%codesavingswhenusingHibernate.

"Many software developers and architects estimate that up to 30% of their code is needed to deal with this infrastructure concern."2

• JDBCandSQLrequireJavaprogrammerstobefamiliarwithrelationaldatabasedetails.

• HibernateallowsJavadeveloperstopersistJavaobjectswithlittleornoknowledgeofSQLandJDBC.

• Italsopreventshard‐codingSQLintoJavaapplications,whichreducesmaintenanceissuesassociatedwithunderlyingdatabasechanges.

• JDBCworkistediousanddivertsprogrammerattentionfromprogrammingbusinesslogic.

• UsingJDBC,programmershavetoconstantlyconcernthemselveswithbindingqueryparameters,writingSQL,executingqueries,scrollingtheresultsetandretrievingtherequireddata.

• Hibernategreatlysimplifiespersistenceworkmakingsimplesave,update,delete,retrieve,etc.methodcallsonobjectsthataremappedtothedatabase.

2www.hibernate.org/about

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-19

• Javaprogramsareobject‐oriented(oratleastshouldbe)innature,whereasrelationaldatabasesaretabularinnature.

• Asshownabove,thiscomplicatestheobject‐relationalmappingandforcesdeveloperstothinkaboutproblemsintwodifferentways.

• ORMframeworkslikeHibernateallowdeveloperstofocusonobjectsandobjectmodelsandnottabularstructuresanddatamodels.

• Furthermore,ORMframeworkshelpalleviatetheORM“impedancemismatch”thatmakescodingfasterandimprovesmaintenance.

• TheORMframeworkcanalsohelptoisolatetheapplicationfromdatabase‐specificintricacies.

• Finally,anORMframeworkcan,insomecases,improveperformancewithappropriateperformanceenhancementslikecachingormoreefficientSQL.

ObjectPersistence

1-20 Copyright©Intertech,Inc.2014 Rev:3

Java Persistence API (JPA) 

• JPAisaJavaspecificationformanagingJavaobjectsin/outofrelationaldatabases.

• Inotherwords,JPAistheJavaspecificationforJavaORMframeworkAPIs.

• Thefirstreleaseofthespecification(JPA1.0)wasmadeinMay2006aspartofthenewEJB3.0specification.

• ThelatestversionofthespecificationisJPA2.1(releasedApril2013).

• TheEJB3.0specificationsimplifiedtheEJBpersistenceAPI.

• RecallthatKingandothersbelievedtheEJBcontainer‐managedsolution(EJB2.x)tobetoocomplexandthatitexhibitedpoorperformance.

• ManyHibernateteammembers,toincludeGavinKing,werepartoftheexpertgrouptoimproveandsimplifyEJBpersistence.

• Startedin2003andcompletedin2006,JPAwastheresultofthatwork.

• JPAisconsideredthepersistencesolutionofEJB3.0andareplacementforEJB2persistence.

• Notsurprisingly,manyofthefeaturesfoundinHibernate(andotherthird‐partypersistenceframeworks)wereincorporatedintotheJPAspecification.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-21

• Infact,Hibernateisanimplementation(orprovider)oftheJPApersistencestandard.

• JPA,asaspecification,requiresanimplementation.HibernateisamongthemanyimplementationsofJPAtoday–albeitthemostpopularimplementation.

• YoudonotneedHibernatetoperformpersistenceviaJPA.YoucoulduseanalternateJPAimplementation.

• Likewise,itshouldbementionedthatyoucanuseHibernateinanon‐JPAway.

• Hibernate’sAPIsupportsJPA,butyoucan(andoftenwill)usesomeofHibernate’snon‐specification‐definedfeatures.

• Youwilllikelyfindthatsomemappingorperformance‐tuningoptionsareonlyavailableinHibernate’s(orotherORMframework’s)implementation.

• Hibernate4.2supportsJPA2.0(releasedDecember2009).

• Again,thelatestJPAspecificationis2.1(releasedApril2013).

• Hibernate5(notyetreleased)isexpectedtosupportJPA2.1.

ObjectPersistence

1-22 Copyright©Intertech,Inc.2014 Rev:3

Hibernate Projects 

• TheHibernateframeworktodayisactuallyacollectionofprojects.

• AtitscenterisHibernateORM(formerlycalledHibernateCore).

• HibernateORMprovidesforJavaobjectpersistenceasdescribebyORMframeworksabove.

• HibernateORM(version4.2)requiresaJavaSE5orJavaEE5platform.

• TheHibernateORMprojectisthefocusofthisclass.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-23

• HibernateShardsisaframeworkthatsupportstalkingtomultiplerelationaldatabases.

• Whenasinglerelationaldatabaseistoolarge,oryouneedtoseparatedatabyclient,region,etc.ShardsextendstheHibernateAPItoworkwithmanydatabases.

• Shardsaddssupportforhorizontalpartitioning.

• Horizontalpartitioningisdefinedasthedivisionofalogicaldatabaseintodistinctindependentphysicalparts.

• Essentially,horizontalpartitioningisaboutputtingdifferentrowsintodifferenttablesindifferentdatabases.

• Forexample,customerswithnamesthatbeginwithlettersA‐Mmaybeplacedin

onedatabase,whilecustomerswithnamesbeginningwithlettersN‐Zareinanother.

• HibernateSearchaddsfulltextsearchtoHibernateORM.

• Searchallowsdeveloperstoaddannotationstopersistenttypesandthenbeabletomakefreetextqueriesonthedatabasetoreturnobjects.

• HibernateSearchmanagesthedatabaseindexsynchronization,translation,andoptimizationtransparently.

• SearchusesApacheLucene(opensourcesearchsoftware)underthecovers.

• HibernateToolsanEclipsepluginandAnttasksformakingworkingwithHibernateORMeveneasier.

• ItprovidesasetofGUIwizardsforgeneratingHibernatemappingandconfigurationfiles.

• ToolsalsoprovidesAnttasksforgeneratingandreverseengineeringdatabaseschema,mappingfiles,andJavacodefromotherartifacts.

• YouwillseeHibernateToolsinyourlabwork.

ObjectPersistence

1-24 Copyright©Intertech,Inc.2014 Rev:3

• HibernateValidatorprovidesdatavalidationtoJavaobjectsinanyapplicationtier.

• ThisprojectisanimplementationofJSR‐349BeanValidation1.1(previouslyJSR‐303BeanValidation1.0).

• Specifically,itcanbeusedtopreventbaddatafromenteringJavaobjectsthatarepersistedinarelationaldatabase.

• HibernateObject/GridMapper(OGM)isaNoSQL/BigDatasolution.

• NoSQLandBigDataaretermsusedtodescribedatastorageandretrievalsystemsthathavealooserconsistencymodelthanrelationaldatabases.

• Dataisoftenstoredinkey/valuestoresversusrelatedtables.

• Theyareoftenusedforlargerdatasetsandusuallyoffersignificantperformancebenefits(atthecostofeventualconsistency).

• ThemonikercomesfromthefactthatmanyofthesedatastoresdonotuseSQLasthequery/interfacelanguage.

• DatastoreslikeMongoDBandInfinispanaresupportedtoday,butthehopeismorewillbesupportedinthefuture.

ObjectPersistence

Copyright©Intertech,Inc.2014Rev:3 1-25

Java ORM/Persistent Frameworks 

• ThereareseveralpersistentframeworksandORMoptionsinJava.

• JavaDataObjects

• iBatis/myBatis

• Castor

• OracleTopLink

• SpringJDBCModule,SpringORMModuleandSpringData

• Andmanymore(seehttp://java‐source.net/open‐source/persistence).

• Somealternativesareopensourceproductsandsomearecommercialofferings.

• JDOisanotherpersistencespecificationandrequiresanimplementationlikeApacheJDO.

• SomeoftheseframeworkshavebeenaroundlongerthanHibernate.

• Ofcourse,thereisalwaysJDBCandSQL.

• TypicallyusingtheDataAccessObjectdesignpattern.

• DAOoffersaverysimplemethodofmappingJavaobjectstodatabases.

• Ingeneral,Hibernateisconsideredhighlyportable,providesgoodmappingflexibility,andgoodperformance.

Lab Exercise – JDBC Lab

ObjectPersistence

1-26 Copyright©Intertech,Inc.2014 Rev:3

Chapter Summary                  

• Persistenceisthecapabilityofacomputerprogramtostoredatain“non‐volatile”storage,allowingthedatatoexistbeyondsystemshutdown.

• Objectpersistenceisdetermininghowanobject’sstate(datastoredinmembervariablesofanobject)isstoredindatabasetablecolumns.

• Gettingstate(data)andassociationsfromobjectsintorelationaltablestructureandviceversarequiresalotoftediousprogramming.

• Howobjects/databasesdealwithidentity,inheritance,polymorphism,associations,andsize(granularity)areallfactorsinthedifferences.

• Incongruencebetweenobjectandrelationalstructureshasseveralnamestoinclude:

• Impedancemismatch

• Object/Relationalparadigmmismatch

• Object‐datadivide(ScottAmbler)

• ORMframeworksprovidetransformationsbetweenobjectandrelationalmodels.

• ORMinJavameansproviding:

• AJavaAPIforperformingdatacreates,read,updateanddeleteoperationsonobjectstate(withoutdirectlyusingSQLorJDBC).

• AJavaAPItoqueryandinstantiateobjectsbasedonqueryresults.

• Ameansformappingmetadatainobjectstometadataofthedatabase.

• Amechanismforhandlingtransactionsacrosstheobject‐relationalenvironments.

• Amechanismforhandlingconcurrencyandcacheissues.

• Hibernateisanopen‐sourceORMframework.

• HibernateisanimplementationoftheJPApersistencestandard(JPA2.0).