Spring JDBC
AI-enhanced title
fr nonasect Query we genera the sb tesa nner clases inthe DAO dls (Fin ere ab ses wa give O5SQL query ther super cae (SiGuery>[agUpaate Ges ony Horne, sot alecing con bjt From be con pol cresting PepeedSaterent jc having en quey ape ompled SQL sty oppo ony for ne nd sb eves ojos sts representing pe orpled Guo, So that ORO das methods one the objec of ECs formulates to exacie te pre compiled £0 ques fr mupletine. Selavery
Ac] whieh ‘avn le oof sera mathode to iplomer®. "ro spagranonas te af eMEPRaeauey iP ameteT> Srospegionenot estos Mapergsee T= ‘onthe each select aque relatd sib as 0 of satanerycP>/Mapngsa!QueryT we can call 3 Ustt> excite.) te Select ory gives uch of recor } conection) Aha Slot Query gives sng record ‘@nepouty(‘udDA0") publ cps SttertDAOInpl pleat StatertOAO{ inate sn i ting GET STUDENTS BY ADDRSWSLEC SNO SHAME SADO AVG FROM STUDENT WHERE SADO=?; prkateStuentelcor slate; erred pute tosenOAOImoaaSource ‘elecor-ew StdentSelector(@(E_STUDENTS_BY_ADORS) Vieersester Lnstes, pt Uerademao> gestadntsbyndeastg ade, UnstuntB0>RtnOvslactr. neta: tum it80; , sb ls os ame ss in ORO atlas stuensooctor extends Mappgseiquey students concer, pe Stadertselctor(Oetasource dy Sting quer seprnveyh ‘pr decareParameter(new Parameter Type. VARCHAR); /regaveingparan(?) with Wb type Sepercomple Pb Sudett0 mapRow{ Resse totum) tows SOL ceo “omer Ws rect 80 coo) “iden nore tser800s besetsnarget) everett) oseseeletsg setae gett) imap) Wier ss ono das Flow of axeciton 0c conaier ration > pro nsanaton of sgt scope beans, 5005, DAD cases preinstarited and 5 Insta t0OAO —> neat proces DRO constr excites an eal sb sim nner cis (Stodertseletr) constr de tots 2 cm nner ‘ds [Saderseetrt) ves OSquery tos super ds MappingsQLQvey) ony for ime and creates Proparetatement ot by aking ‘ren Sl query ar pre-comole very bear of sper comple) ony for Sime 8th end the abs cum inner cia (stdenteecar) represents precompleg al ger) Sec cas method cals OAO method (gtstudentsbyAdr) formless selector. creat ao call formule ‘imes->in thi procs values to quar pam wil be stor maps times > aor xeon take pac fr mule imes—> srerig 5 ol processing tat ob to Ust8O by alg maptowt) taker ac for multiple mer returns UsBO back o RO cass method or mute tines. ‘outering end sing 05 happens for Ye (0) 1) Gathering econ object rom be con pool happens for ne) ‘creating Preparetataren iby making the 80 quay a pre-compid SOL query happans for tine (0) 6 seing vats query pres and executing Query happens fr matpe tes (Cr ©) georges are processing resus happens or maple es (X)Woking wih properties fle and yri/var fies in sping/sring boot ‘we can red inputs from properties f/m feo sorrg bean properties in two ways ‘s]using value (ven ping ra ooes not support bulk reading) “Swe soul ad on th top ofeach propery ending ales into aray/is/set/map nd WAS Objet complex (nt recomended oda} “Spropety name in bean lst and Key in proppetos ym fle nee not match ‘yl >ylant markup langvage/yamaing markup language. | A dferen approach ‘yaryetanther markup language. ‘maintain keyrvahes option properties (sping boot plan aptiaon property le wl ‘utomatcaly 25 pa applaton flow rom se/main/resources flee) Inote: the propectes/y les having other name oreation ‘must be conigred expt using @Properysource, ‘nnotaton] pecinfoidet0n erinfo.namesrae Lecomponent @osts pute css Porson (@value(serntosar) privat pet (@Vaues(orintonamey) private sting pram, ) 2) @configravontropertes (supports Bulk reading) ‘Dive by sping bot 1.0 ‘=>Allows to read values into simple, array/list/set/map , HAS-A object properties ‘sateirmataia leemypeneeny elepting ecincianitn pacientes. ‘Suereedts anion the op of ring bean ca by ecg pref So @van @contguatetroperiesindaty tom top afb da) tes eee es oa thoes ct ae ban sopteatn groperien Patios e owe bexinfoda0s ‘Scomponent pe per {Scortewreontroperieoata="prinf") We wore wth @canngutnProperies hs rcomande to athe folowing bated Penent “ependncy poms eo genase Metro show ets fayroh vse pein”) ‘powprie/ yn te bse tot ah waings proper wl go tet fle 01 a fala, deoandener “poupldorgapdngramauerboseoupi ) Person ave oa ‘@component"per) (2 coniguraonProperiesoreti= publ clas Person Healt Spero") priate it nfosmartsieS0 Privat Sting name; infosmarsi2I-60 priate suing eds: ‘lle properties (et varevaue) ‘is coection ipretivarlindox-raie) perinfomerts2(0}50 Private Job ob; /7HAS-Arolaton property se cotetion pretivarindextevatue) infosmarss0]-60| perinoarta[1}-70 infosmars3 21-60 snap collecon/Properties [prefer kewale] er ina.phones prsonale777777 ‘SHAS. Relation Object type property ori Mas Avar.var=al] erin saarye7788.6 ‘inmost cates wo we pre-eflend keys and ther values in aplation properties to provides instructions /nputs related ‘autecontiguration. ‘She Boans of AutoconfrtionItemally wos this @Confguationropetes to reed values rom propeites. orample {econiguratoneroperiesoetice rng dso pubic cu DatasoucaroperterimpiamontsBesnCaaoaderwae inabingbea ( , white praparng element values to aay/ls/st cole Ine syntax ropes Me shown blow ‘ay/set/s Cllecton (pei. verlnderovalve.valve vee) ecinfomarks3=50,70.80,YML/YAML => Yiant markup language / Yar markup language (ymi) ‘= Yet Another Markup language (YAML) = Alternate to proeperties file , vary useful when lengthy keys at same level hecoz it avoids duplicates from the keys by maintaning key and values in hierarchy manner. iin i fope6-101 | se worif ge freee forme met iicomcnamernis | Wht: tae sgn teye info: | levelt node | lovel2 nada] Here the word “hfo,per” isnot repeated inthe keys by serrne rmaintaing data as hierarchal dat. name: raja ade: hyd ‘= extension can be .yml or yam => spring boot internally uses "snack yaml api” to parse and convert yml file into properites fle => while writing "nodes" in ymi file you must give minimum one space and allowed special symbols. In the keys are "_","-"/"." => same levels nodes must started at same place(same col number in the fils {this indicates we must maintain proper indentation) ‘= Both application.ymil or application.properties will detfed and loaded by spring boot automatically during the application startup... from main/java/resources folder. => we can bind yml file data to spring bean class properties/varlables either using @Value(given by spring) or using @ConflurationProperties(given spring boot) annotations ‘=>yml files are node based, space sensitive and indentation based files. If not errors will comes. application.properties = pplication yl info;eri01 info.pername=aja kasicbiaeaeci ‘symbol in properties fe, inf job salary=5000 ‘if incicater comment company ostomy company namacic. pen ‘desg: clerk ‘aay: 9000 company Tocation: hyd same: Het array/list /Set Collection applicaiton. properties info.per.marks[1]=70 info.per.marks{2]+80 ‘pplication. yl ‘Map/Properties Collection application.properties # prefix.var.key-value Info.per.phones.residence=999999 info.per.phones.office=88888888 info.per.phones.personals7777777 application.yml info: per: phones residence; 999999 office: saa8e personal: 777777 ‘acts keys and values in map collection (Map Collection). keys values ‘use properties fle Ifthe keys are smaller and the nodes/prefixes are no repeating. ‘use yl file ifthe keys are lengthy and the nodes/prefixes are repeating Object type for Has relation property @vata @vata @Component{*per") ae public class Job { pplication. yi @ConfigurationProperties|prefix="info, plete shag iene oT public class Person { private float salary; ™ private Job job; private String company; a } private stringf] skills; ‘dese: manager : salary: 8999.5, to convert =n Eclipse IDE therre is bultn convertor to given properties file to mi file ht click on properties file —>convert°ym file. Internal flow of @ConfigurationProperties and @Value 41 Spring boot detects and loads applicaifon.properties/ymi fle LiF it ym file it will converted into ropperties file intenrally using snackyml 143 Collects the values from Envirmoment object and binds to Spring Bean class obj properties, based on @Value or @ConfigurationProperties annotation, Person das bilprinbean) @Component("per") @vat @ConfigurationProperties(prefix="info.per") public class Person{ #2 reads keys and values of properties/yml fle Into Environment object (InMlemory object cre: In 10¢ container) private inti Private String name; This env.. object holds multiple details a =>properties/yml file data : system properties , ‘env.. varlables info ike PATH, CLASSPATH and etc. profiles info If we place both application.properties and application.ymi files in spring boot application having. same keys and different values then what happens? ans) The values kept properties file will be taken as final values.. note:: if certain key is not avalable in application.properties file, it will be gathered from ‘application.ymlWhat are the afferencs and siniliaties between properties fle and ym! file ‘bet iteree: yantiont sae gtepelen nan ne ie Po, Ray > Sac Faneee doa sppr GPopeSoucs iy 5 Hosea wing ras of, ou canhve lig ofieince le yl Se ce jemeconinear ° When should use properties or ym! file? ? ‘doy any esp ie ES Syren agp ae Bese ema seb iio separ Pryor opr Se Ex grofenedcoe pate roe le «= if keys re lengthy having mutuple common modes then for ym fs becz It avolds the repeatation of common nodes. otherwise go for properties fle Whats the cfference b/w @Volue and _@ ConfigurationPropertes? ‘@value 2) given by spring framework 2.0, Sot can ‘be used in both spring and spring boot programming bjuseful for reaing single value trom sproepties ‘or yet fle «) canbe applied at -mathod level and field level param level and et. (but ot thas level 4) Common prefix not required to read values ‘rom properties or yl fles properties or ym file, @confguravinPropertis a) given by spring boot 1.x, Sot can be used only In spring boot programming [+ useful for reading bulk values by giving common prefix from |<) canbe applied only on cas evel and method level |) common prefix is required «allows to use SPEL (sping expression language) |) Not possible towork with SPEL allows to work with aithmetie apd logical operators, Profiles in spring /Spring boot ‘>Envirmonment isthe setup that requlred to execute/test the application/project ‘Fora s/w project we need to have diferent enviroments er profiles they are Developmen Env. [required in project development) Testing of [required in Project Testing] See pea carers cre io = Dev env.. Testing env. UAT Env.. Production env.. Qs cee sino snes om vtec ae with €3P0 hamelaer apache DBC hikari me & nm rid rersot ————iin employees clentorg ca eeeeee ae eee eeenyararnemgmeeme lg aioe Seereat ae oe in tana te ‘ofthe we can develop multiple properits fils for multiple env. /prfles on 1 per env.,/proile basis land we can activate one e syntax: /orfile based onthe requirement. ‘application properties (er) application properties application properties/ymt (base/ default properie file) ‘pplication dev-properies/yml (for dev env/profile) _applcation-testproperties/yml (fr test env/profile) _pplication-ustproperties/ym (for uatenv/proflle) _application-prod propeties/yml (Yor production enw/profile) ‘To make spring beans working fr certain profile we can use @Profle annotation onthe top of stereotype annotation based springbean classes or @Bean methods of Configuration cas. @rrotte((ust’ prod") (@Repositor("eraCustDA0") Public class OraclecustomerDAOImplimplenents CustomerDAO{ @Profle((dev"“test") @Repository" mysalCust0AO" public class MysaicustomerDAOImplimplenents CustomerDAD{ @configuration {@componentscanfbasePackages="com.nt.dao") public class Persstenceconfig, @Profle( ua e@pean public DataSource cresteApacheD8CPDs(} st) , (@8ean e@Profle("dev") public DataSoruee ereatecaP0Ds (i ‘obean {@Profle("prod”) Dublic DataSource createHXCPOS () } Uidiass To activate spec profile dynamically at runtime using base/default profle/ymi fle (best) application properties ‘ppication.ym spring profes. acivesdev | spring: profiles: ‘active: dev Using command tine ag (optional ares) spring profilesacive=dev In ecpse IDE run AS—>Run configurations —> ‘arguments tab —> program arguments (commandline args) \VM arguments (system propertes) Using ystem properties (VM arguments) “Dspring profesactive=dev a naciar -Dspring profiles active=dev "Example App on spring profile using spring boot 43} keep spring boot mini Project ready add ational jars/dependencies in pom.xmit > cpD, apachedbep2 €)G0 0 DAO classes... write code with dbeTemplate and also specify {@Profile onthe top of castes. eProfile((uat prod") @Repositery("oracustDA public cats OracleCurtomerDA0Implimplanents CustomerDAD{ @Autowired private IdocTempate ft » 4) develop multiple prosprie les for multiple profiles ax show below. application-dev.properites sOatasoruce cfg for dev env. (C3PO, mys) ‘pring datasource driver clats-namescorn.myscl.c jdbc. Driver spring datasource.urt|dbe:mysa:///msp7134b spring dtasource.usernamerroat Spring datasource.password=root ‘make spring boot work with e3p0 by breaking default algorithm spring datasource.ype=com.mehange.v2.c3p0.ComboPeoledDatasource applcation-vat properties nbatacoruce cfg for dav env. (apacneDECP oracle) spring datasource drverclaee-name-oracedbc. driver OraclaOriver spring datasource.urlsjabcoralethn:@localnost:152 spring datasoure.username=syster spring datasource password=manager ‘make spring boot work with c3p0 by breaking default algorithm spring datasource.typesorg.apache.commons dbep2.BaseDatasource stop) activate one profile from application properties application. properties iaiiate proto spring pofiles.active=dev (@Profle((dev" test") Repostor(" myselCustOAO") public cass MysaacustomerAOImplimplenents CustomerDAO{ @Autowired private JdbcTemplate jt applicaton-est properties atazruce cig for dev env. (apacheD8P, myst) sping datasource driver elas-name=com. mys. jdbe-Drvor spring tatasource.urljdbe:mysa:///tsp7134 sping datacource.ureramenroot sping datasource.passwordsro0t sake spring boot work with c3p0 by breaking default algorithm spring datasource.type=org.apache.commons.dbcp2.BasieDataSource rod. properties abatasruce cg for dev env. (HkiarCP oracle) ‘pring datasource drive-clas-name=oralejdberiver-OraceDriver spring datasource urlscbe-oracl:thin-@localhost-5216 ‘ring datasource. ueemamencyetom spring datasource. passwordemanager‘Tatung spring boot profiles as ymat application-dev. ymt ‘epplication-test-ymnt sere sey: ‘ateouree thseource hives ame: com mys le Deer ver cas ame: com myslejjdbeDeher fmeeoh ont ord rt ‘ype: eommerange x2 3p0\Comborooledbatscurce "ype orapache commons dbep2 Basebaasouce em 2 carps? sppaonat. yn spplaton prod yn tasers: = ier ca ame: rade camer Oracle eros: manager ‘ype orgapache commons bcp RacDatascurce Li jdoconcieminenocatnastis236 ve as name: erade jibe OraceDdber Ui Jodcoradeahineocahos:1s2te etre stem sppaton yal sev profes athe: dev Weting multiple roles wing single yr fe song: iotes dey “vrs name: comms abe Driver passwort rot ‘ype: commehange v2.90 ComboPoolaDetaSource ‘ot obey 0 act saperatr .murtbe a bepnng song: =s “ivrlas-rame: com mys dbe river passwort type! org apace. commons. dhe. BaDatasouee (obey ets rng: Etasoure “hverloss-name’ race be diver OraceDtver prsswort manoger "ype: org apace.commons.dbe2.BasDataSource Uh beonderhinglochost 521% “iomame: sytem rng: ‘atasouree “er clasename: eae be dior Oraeoever passwors manager Ci obcondesthinetocahost 52116 “iomame: sytem ‘Working with Profan 100}Codediven onfguraore step keep 100% code even contgrations MinProsj ready stop2} add apache ob 390 ihr as bul rele or pom. fhe '20p3) make sure that OAO clases ae inked to prlesproper.asng @Profle erroe(Cvat re) (@nepestor(orscustDAO") pubic cs Oradeustomer0 AOI! implements CstomerDAO{ > ‘ereportor|"myslcuxt0 0") errotllCcer ese) public cis yielustomerDADInpl implements CustomerOA0 f , stepd)_ Develop Persstecontg asshavng Bean methods Unked with Profs, Portcenesconf.ve ‘@configuration (OcomponencarfbnePackages="cor..deo") Dube cle Paritenceconig( @vean Brrfietder) bile OnaSource cestec2PoDs( tows Exception Sytem.out pti ParsistanceContg.createc3POOS1) ComborooledDstsouce denew ComboPooledDeaSource), esetrberinl comma be Dee sean (QPrtinlt0ay) Dube Daasaurce ceatenpacheDcrosaysal) tows Exception { ‘tem.cut pnt PerstenceConti reatehgacheDSCPOSMSgI)") Buacdatasource bere BaseDatasouree); bissetDrnerlssName(‘com myseobe Dever, besaetba edema p73") bessetdsemamat Tot: bessetrasword rot) ) @0ean (Sere uat) ible Ontasouie createapecheD¥crosoracl tows Excapton{ Sytom.cut. pnt PeritanceConfig.createApacheD8CPOSOrec") Bescdetasouce bien BascDetaSouree bissetDiverlssNare oracle be rer. rade") bassetua Jobe rae eloahost 52130"), betsetUserama( stem") bssetPassworemanaee) retwn bas ) eseen (ere pr Dube DataSource ceateecPOs) vows Exception { ‘Sytem cut. pt PerienceContigcresteHtCPOS(; iaribatsSoureehr=ne HikarDatsourcel) setDrerleaName oracle jb river raleive") hceetdbcibcaralethin-plocshont is." asstusemama')ten" hessetPessword manager) ) eeean elle ule lebeTemplatecreat!TUsngC3POd) tows Exception { ‘sytom.cut pin Perieneaconi ‘ean "e390D5" Clss-com mchangev23p0.ComboPooledDatasouce"> | “Seams waft n> ‘ “propery namse"drecleetare” valuscom mye) be Driver /> “proper ramen"u” value’ Jbermyag///sp723@b"/> “Srna ames"bsn ve ot/> “oper ramessememe™ veo ~ Sropery ranesrpmed va or > co “ean des aspnfamener te crecremplte> “ean aon spratamewert be coe sbeomplt'> “conscara cPaoe > “conor ee ebepoee finns ime. “Toros-omponentscn ate gacagensomte0/> - — ‘i ina Pee ana eine bans adel aaa ‘Some pomeeee o> “Sear nde” cso ae her kerDetasore™> “ “property names"diverlesNome” vlueovcle fc diver OraeDiver > “propre ames"u value= jbcaroclethin Gloeaost 1521%0"/> toe contr componente be phage com - - sania sivcos erro") (@repoatorerscst0A0") Dull ss OredlestomerDAOIml Implements Customer DAO { , posto mysCutDAO") ferrtie(ev" te) public css MyaeiustomerDAOInpl implements CustomerOA0 > sten8) Activate profi from Cent Ase ‘inapathxniapocationContertcbmnew Casathkmlappentoncantent( ‘onigurbegnvronmen r+(ongurabeeneronment) i. gervenmen Tsetacive pte rei ‘setConfigcaticnzon/n/tg/epplcatoncontxten), courts 1] getContrler Bean css bj. Mainconraier crtaiar = ce getBea( "coo" Manco.)