You are on page 1of 2

RecommendedforYou

ONJavaTopics
AllArticles
BestPractices StoredProceduresforJavaProgrammers Print
EnterpriseJavaBeans SubscribetoONJava
JavaandXML byNicFerrier SubscribetoNewsletters
JavaDataObjects 08/13/2003
JavaEE(Enterprise) ShareThis
JavaIDETools ThisarticleexplainshowtouseDBMSstoredprocedures.Iexplainthebasicsandsomeadvancedfeatures
JavaMedia suchasreturningResultSets.ThearticlepresumesyouarefairlyfamiliarwithDBMSsandwithJDBC.It
JavaSE(Standard)
alsoassumesyou'refairlycomfortablereadingcodeinaforeignlanguage(thatis,notJava),butdoesnot
JavaSecurity WebScrapingwith
JavaSysAdmin
expectanypreviousstoredprocedureexperience. Python
JDO/JDBC/SQLJ Print:$31.99
JSPandServlets
Astoredprocedureisaprogramthatiskeptandexecutedwithinadatabaseserver.Youcalltheprocedure Ebook:$27.99
OpenSourceJava fromaJavaclassusingaspecialsyntax.Whenyoucallit,thenameoftheprocedureandtheparameters
P2PJava youspecifyaresentovertheJDBCconnectiontotheDBMS,whichexecutestheprocedureandreturnsthe
WebServices results(ifany)backovertheconnection.
WirelessJava
UsingstoredprocedureshasalotofthesameadvantagesasusingapplicationserversbasedonEJBsor
CORBA.ThedifferenceisthatstoredprocedurescomefreewithlotsofpopularDBMSs,whileapplication
serversaremostlyexpensive.Thisisn'tjustanissueoflicensecost.Thetimeittakestoadministerandwrite
codeforappservers,andtheincreasedcomplexityoftheclientapplicationsthatrelyonthem,canbealmost
whollyreplacedbyarelianceonyourDBMS.

YoucanwriteyourstoredproceduresinJava,Python,Perl,orC,buttheyaremostoftenwrittenina
languagespecifictotheDBMSyou'reusing.OracleusesPL/SQL,PostgreSQLusespl/pgsql,andDB2 JustEnoughMath
Video:$129.99
usesProceduralSQL.Theselanguagesareallverysimilar.Portingbetweenthemisnomoredifficultthan
portingSessionBeansbetweenversionsofSun'sEJBspec.Inaddition,storedprocedurelanguagesare
designedforembeddingSQL,whichmakesthemmuchbetterforexpressingthedatabasemechanicsthan
languageslikeJavaorC.

BecausestoredproceduresrunintheDBMSitself,theycanhelptoreducelatencyinapplications.Rather
thanexecutingfourorfiveSQLstatementsinyourJavacode,youjustexecuteonestoredprocedurethat
doestheoperationsforyouontheserverside.Reducingthenumberofnetworktripsalonecanhavea
dramaticeffectonperformance.
CSSSecrets
UsingStoredProcedures
PlainoldJDBCsupportscallingstoredprocedureswiththeCallableStatementclass.Thatclassisactually
asubclassofPreparedStatement.Imaginethatwehaveadatabaseofpoets.Thedatabasehasastored TaggedArticles
proceduretosetapoet'sageatdeath.Here'sanexampleofcallingthatstoredprocedurewithdetailsabout
theoldsoakDylanThomas: Bethefirsttopostthis
articletodel.icio.us
try
{
intage=39;
StringpoetName="dylanthomas";
CallableStatementproc=
connection.prepareCall("{callset_death_age(?,?)}");
proc.setString(1,poetName);
proc.setInt(2,age);
cs.execute();
}
catch(SQLExceptione)
{
//....
}

ThestringpassedtotheprepareCallmethodistheprocedurecall
specification.Itspecifiesthenameoftheproceduretocallanda?
foreachparameteryouneedtospecify. RelatedReading
IntegrationwithJDBCisabigadvantageforstoredprocedures:in
ordertocallaprocedurefromyourapplication,youneednostub
classesorconfigfiles,andnothingexcepttheJDBCdriverforyour
DBMS.

Whenthiscodeisexecuted,thedatabaseprocedureiscalled.We
don'tgetaresultbecausetheproceduredoesn'treturnone.
Successorfailurecanbesignalledwithexceptions.Failurecan
meanafailurewhencallingtheprocedure(suchasoneofthe
argumentsbeingspecifiedwiththewrongtype),oranapplication
failure(suchasthrowinganexceptiontoindicatethat"Dylan
Thomas"doesn'texistinthedatabaseofpoets).

CombiningSQLOperationswithProcedures

MappingJavaobjectstorowsinSQLtablesissimpleenough,butit
usuallyinvolvesexecutingseveralSQLstatementsmaybea
SELECTtofindarowIDfollowedbyanINSERTofthedatawiththe
specifiedrowID.Inahighlynormalizedschema,theremightbe
multipletablestoupdate,andthereforemanymorestatements.The
Javacodecanquicklygetbloatedandthenetworkoverheadfor
eachstatementsoonaddsup.
JDBCPocketReference
MovingallofthoseSQLstatementsintoastoredproceduremakes ByDonaldBales
lifemuchsimplerandinvolvesonlyonenetworkcall.Allofthe
associatedSQLoperationscantakeplaceinsideofthedatabase.
Inaddition,storedprocedurelanguagessuchasPL/SQLallowyoutospeakSQLmuchmorenaturallythan
ispossibleinJava.Here'sourearlierstoredprocedurewrittenusingOracle'sPL/SQLlanguage:

createprocedureset_death_age(poetVARCHAR2,poet_ageNUMBER)
poet_idNUMBER;
begin
SELECTidINTOpoet_idFROMpoetsWHEREname=poet;
INSERTINTOdeaths(mort_id,age)VALUES(poet_id,poet_age);
endset_death_age;

Unusualimplementation,no?IbetyouexpectedtoseeanUPDATEonthepoetstable?Thisisanindication
ofhoweasyitistoimplementthingswhenyouusestoredprocedures.set_death_ageisalmostcertainly
badlyimplemented.Weshouldprobablyjusthaveacolumnonthepoetstable.Itdoesn'tmattertotheJava
codewhatthedatabaseschemaimplementationis,becauseourJavacodejustcallstheprocedure.Wecan
changetheschemaandtheprocedurelatertoimproveperformance,butwewon'thavetochangeourJava
code.

Here'saJavamethodtocalltheaboveprocedure:

publicstaticvoidsetDeathAge(PoetdyingBard,intage)
throwsSQLException
{
Connectioncon=null;
CallableStatementproc=null;

try
{
con=connectionPool.getConnection();
proc=con.prepareCall("{callset_death_age(?,?)}");
proc.setString(1,dyingBard.getName());
proc.setInt(2,age);
proc.execute();
}
finally
{
try
{
proc.close();
}
catch(SQLExceptione){}
con.close();
}
}

Usingstaticmethodslikethisisagoodwaytoensuremaintainability.Italsomakesthecodethatcalls
storedproceduresintosimpleboilerplatecode.Ifyou'reusingalotofstoredprocedures,you'llfindyourself
justusingcutandpastetocreatemethods.Becauseoftheformulaicnatureofthecode,it'salsopossibleto
scripttheproductionofcodetocallstoredprocedures.

Pages:1,2 NextPage

2015,OReillyMedia,Inc. AboutO'Reilly Community PartnerSites ShopO'Reilly


(707)8277019 (800)8898969
SignIn Authors makezine.com CustomerService
Alltrademarksandregisteredtrademarks AcademicSolutions Community&FeaturedUsers makerfaire.com ContactUs
appearingonoreilly.comaretheproperty Jobs Forums craftzine.com ShippingInformation
oftheirrespectiveowners.
Contacts Membership igniteshow.com Ordering&Payment
CorporateInformation Newsletters PayPalDeveloperZone TheO'ReillyGuarantee
PressRoom O'ReillyAnswers O'ReillyInsightsonForbes.com
PrivacyPolicy RSSFeeds
TermsofService UserGroups
WritingforO'Reilly

You might also like