0% found this document useful (0 votes)
65 views

Spring JDBC

bb

Uploaded by

8el3i6t6wd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
65 views

Spring JDBC

bb

Uploaded by

8el3i6t6wd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 17
Sing 1086 spring 040) [ft provides abstaton on plan 08 Technology andsmplifis be style pesistence lope development by avoiding boiler pate code ‘lain jdbecode (ove J0BC code) “Stone diver as (Tore ever with rverManager Service) create te Statement bck {common ose) ‘osend and execute SOL. query > epter este and proces recat Ui necessary erate tvough RS) (Mop spectitogs) “> pertorm exception handing | pertorm Teg (optional) (common tose) “dose de ob ineading jibe on) common ls» that are same inal db apps (borat code) bpp spectc logs -> wil change based on the Db su we use, ote: The code that repeats across the multiple arts of Project application either wih no changes r with minor changes is called bollerpat code. spring JOBC App Sine bce as internat takes are of bor late codelcommon les} objhaving Datasorace bj “idbcremplate/pring be send anderecate SQL query | (oppiiation Method Gather reat ed rovcr amas | Parag Movie emplate/ seriaich ecteeenterroeciia ie “ommong thing wile taken careinernaly and ‘Spec things wil be vento programe to rotamer Implement] Oy wes plain jd code ==> java code + SL queries (bs) dependent Persistence loge car queries re D8 fw dependent) ring abi5. spring ode abe code + SAL queries [08 s/w dependent persistence oil persstnce The proces of saving end managing a or ong ime Persistence store The lace where essence takes place ees, Dbs/w (ter) Peritenc operations: inser update delete elect operations these areal ald CURD/CRUD operations [GpcteateU-oupdate,R-oRead , Delete Jave Persistence Persistence logic The logic to perform curd operations Se We rigid wd mavione gnc oma whom oeingouann | eater cs itera ay Lae se Soo etn = (eats sian Se trun does treangerany ee buch for procetng BsfwsthengotorBabata rear whet sing pr Aerie opt dg menace Ide emount of dotatoprocessate time {Census Ao, e-commerce Apps) bytaking afr as persistence stare [0 sw dependent Persistence loge) (es cin evn oe sndete) (Were each record willbe represented by 180(jva bear) css) (0Bs/w independent persistence other advantages ke caching pany acttaicsiraay ay notes spring Data module i having capably of pnerting note sping bc internally use plain JOC and js simpli: abe style persistnece loge. 70% spring be wil take cre ‘and 3% shouldbe taken core by programmer) notes spring ORM internalv uss pain ORM and ust sili ‘ORM sve objects based pessinece logic Le | 70% spring ORM wil take care “ed 20% shouldbe taken carey propre) be presence tile ordinary computers called rack "e: Facebook dla, Goole data, {yotube deta andeten Laon with lan 08¢ ©) wes Db sf dependent SL Ques nthe development of Perstence lg So the persistence eg 08s/w dependent 1) Supports ery pstona params (7) doesnot sport rare paras 2) esatst oj hat represents theSELECT SOL Query executors ot Seabee 10 sends 4) We rece wit exp ge to conver Rs abject tears to omats He LstCotecon, Map Calecton, simple ees and et “Jive: boar pate code role Le we need wite to comman ogi very be a9) ‘Mtwows s0LEtcepton wich chechad Exception snd tans re |) oral probies fobe code sare exception 1) We shoud exp eater nd arte the exception 1) Berna suppor Exeption Propagation natura 1) Canomiation reas ry compen spengs08¢ wvontages {2} Supports bot poston 2) end named prameters (Oyen get "SELECT avery" Rests inten formats rectly withthe support of omen nah ere ete ()Ctomiatin rests es wn the supporto Cabck neces {a} Potses abstraction on pin job cate and eas he Boer plate cde common ops be ‘enerted inter) (e) cue eta execepton cases erry whieh ald Datanecesscepon cases Nercchy ‘he atvantages are I} These exceptions re unchecked eeeptions he rect cla of jovelone Seapine 1) exception handing options ‘ecaled Checied Exception. ‘ppor enceonpopepraen by deta. ‘the rect uh ces of jean Rominebxception ca aes torent excoptns for etferent prblams. Urecaled Unchacked Exception, those are sare execpt for ing be ring or an sping data moles sping 1D8 teal ses xcepton etvowing concept to cnet checked exception (SLExcepon) into Uncheced ceptions Ontanecesscepon and sub asses) pubic Object quryorobjectstring quero Oatatcessacaton{ wt lindo code > cuhfsaLeception 5} ‘trou now Oxteacesacopton(e geese ) “cepinrethrowng happening here , (Simp: te proces feallng P/SOL Procedures nd func. (a) Gives gremsupportto work wit Genes vr eg and ete. Goes feats) (h) Alows to work th ovat.2n0 ard ete features. (Can generate insert SOL query dyareaybatedn the gen beable name, teas note: spring 08 Parsee loge ft 8 s/w dopondont Prange Bec Ts SOL queries bated Porssece loge Diternt Approaches of developing Pestnce lope sing OBC 2) Using aberompate 1) Using Namedrarametenicterlos 6] Using simple Temples (sopractednsring xan removed in sping 3) 1) sing Simplebnsar, smplndbca ©} MappirgsaiOperations 5 sub clses a) Using JdbcTemplate ‘its contra Gas/AP das for entre spring DBCL remaining approaches of sing OBC Programming intra wee th beter Desgne based on Template method den pattern which sy fina algrthm to complete {tank hare common aspects willbe ten carey sping bean lets the rogamene take (ref ny sec ees. Neced DataSource bar Dependent objet. ‘ves quer) end queryoront) for slat Ques Exception and gies paste) method for noseect eres execpt, “>idocTompat suppor oly Postal prams ‘Whats the jc con pool/DataSource that sed in sing Project? iter quer queyforina) of bctomate ‘as stasoruce oboe represents be con poole all operations on be can poo can be one trough Daasonce obec. eel 2} To gtsingle value org objec we cueryFovbject) ‘eis elect cour" om emp S52 select orame romemp where mpno=? ces sectempronameysbual rom emp whereempno=?\Ciesa-So00 Tote get es value of recor ito 80 cas ob) 2) Tope single recor into tp Colton use queremto() it projct or appcaton standalone thn se ia be or pace pi select emframe ol rom emp where emp? ep, oF 0 oF vib por tomeat psd et Mancahecion ‘itn Project or appicaton web aplation and dplyate nthe server Ihe tomeatebogosih and ete tense Servet manages on pol tomeat managed bec pal, wet be cn pool and ete kee 13) Toget maple rcodsito Ut Cleon wie querer eathog ‘gh sletempro.anamajobsl fom emp where Job=? Li catecion andere We can use dbeTempat into anys ine ets havng Ug et mate jamaica ewe nee "> Togs cooic rents ‘>rogetrenite angen sr randes by wing port ‘bymethods me obec re brea be Jae coe. by tinng the ery Map stand te. me persistence-beans.xml ‘beans> applicationContext.xml queryForObject{-) gets the Injected DS from jt —>Ds collects one jdbc con obj from jdbc con pool —> creates PS(PreparedStatement obj) having given SQL query as pre-compiled SQL query-> executes query using ps.executeQuery() and get RS(ResultSet) object—> calls rs.next() and rs.getint(1) method to get result as int value becoz of required type Integer.class —> result to DAO method ->DAO method gives to the caller service class method. =>idbcTemplate internally uses SimpleStatement object to execute the given SQL if the query is not having any positional (?) params... otherwise it uses PreparedStatement object countsjt.queryForObject( "SELECT COUNT(*) FROM EMP", Integer.class); It internally uses SimpleStatement object (static query) String name=jt.queryForObject{ "SELECT ENAME FROM EMP WHERE EMPN( ?", String.class,eno); It internally uses PreparedStatement obj becoz supplies query the SQL query is dyamic SQL query (query with param values parameter) @Override public Map getEmpDetailsByNo(int no) { MapcStringObject> map=null; map=jt.queryForMap(SELECT EMPNO,ENAME,SAL,JOB,DEPTNO FROM EMP WHERE EMPNO=: return map; , ay 7 Map object (String,Object) GER] _ (ResultSet 7499 ALLEN CLERK 6000 10 |r.) * no); key-col names. value- col values @Override public List> getEmpDetallsByDesgs(String desgi, String desg2) { return jt.qleryForlist(SELECT EMPNO,ENAME,SAL,JOB,DEPTNO FROM EMP WHERE JOB IN(?,?) ‘ORDER BY JOB" desgi,desg2); List Collection join Map object = — Map object Map object ‘Map object ‘Map object Converting spring JDBC App into annotation driven cfg based App ‘Thumb rule configure pre-defined classes as spring beans using, tags refer DAOP9}2-Anno-IdbeTemplate-DirectMethods = confugure user-defined classes as spring beans using_ stereo annotations and link them ‘with configuration file (xml file) using tag. Converting. Spring JOBC App into 1002%Code Driven efgs based APP Thumb rule: es refer DAOPoj3-100pCode-JébeTemplate-DiretMethods refiners hin cant iguration cate Gang @comPorantseat Ramos =Configure pre-defined classes as spring beans using. @Bean methods in ‘@Configuration classes => Use AnnotationConfigApplicationContext class to create !OC container. Converting Spring JOBC App into Spring Boot App ‘Thumb rule: -=>Confleure userdefined classes as soring beans using stereo tvoe annotations smake sure that all packages ae placed under starter/main class package as sub packages ‘Configure pre-defined classes as spring beans using @Bean methods in @Configuration ‘lasses only if they are not coming through AutoConfiguration. ‘= get OC container using SpringApplication.run(-) method.. If add spring-boot-starterjdbc to spring boot projectwe following classes as spring beans ‘through AutoConfiguration| 2) HikariDatasource rofer DAOPoj4-Boot-JdbcTemplate-DirectMethods b) JdbcTemplate JNamedParameterldbcTemplate 4) DataSourceTransactionManager ‘and ete. Limitations with _JdbeTemplate Direct methods a) query{} ayeryFombex(,) are giving "SELECT "SQL query results in diffrent formats.. but stil they ard industry standard becoz of memory wastage.. -=>queryForMap() gives single record as Map object having col names as keys and col vlaues as values. here col names wasting the memory... The industry standard is getting record into BO class obj = aueryForLit() gives multiple records at Map objects stored into the List Collection .. But col names in all Map obje ‘are wasting the memory. The Indurstry standard is List Collection with BO class abjece.. Map object “Hanae. fom | 7999 List of 80 class obs a vename| ALLEN . : aS ee) pcx — (Memory is wasted in every Sache (Good) (Memory is not wasted for col names) 1) No ability to use our choice JDBC statement objs to send and execute SaL queries in D8 s/w. ‘) Customization of Results (SQL Query results) Is more required. Toovercome the above problems.. use dbcTemplate methods with Callback interfaces. Jdbetemplat Direct methods Alctemplate rect methods with with ot callback interfaces Cahockimertaces isin 08 code —— : bellerplate code problem = Nosolerplate code aes provides abstraction on plain JoBc —-—«>N2Bilerpatecode problem oainte programmer to doevertin Therein ineletraes ——Povdesabstacionn plan DBC code Pano progan ing folocae eee Roane ale sue Curation omit tic are not indus stander parameter of clack methods by fe ed ste ‘creating them internally to customize as per industry standard like BO obj, (saying in hostl with Peper hemp ariege eapal Uistboobisand ete ee Steeles, rye (staying in Flat with self made andete- pal {Staying nose taking hostel food relbicie boy Weep at food] Calbock method :| The method that executes automaticaly i called Callback method this : mee= method wl be calle by anderying en ite Spring O8C or Container or To or server astomatcal Callback Interac: The interface that contin the dl of callbckrmathods ical Callback interac. Sere ite yce methods ar called Cotnainer Spring 8 i proving multiple callback nteracs, they are callback methods. becar we donot cal them they willbe called SerletContainer automatically for different if cyte events. {2} RowMapper : Gives RS obj to customize single record/row (like 80) byResultsetBxractor ves RS object to customize multiple records ke Ust80) ->stateless ‘RowCallbackHlandler: Gives RS object to customize multiple records like ListB0)->statefull ‘dPreparedstatementCreator: gives jdbc con object to create PreparedStatement obj ‘¢)Preparedstatementsetter i gives jdbe Preparedstatement obj to set values to query params and to execute Query ‘statementCalback 1) ProparedstatementCallback ‘ncalbablestatementCallable ‘WPreparedstatementBatchSetter andte. RowtappercT> ‘> callback method ie public very useful to convert RS obj single record to BO class obj overloaded formshaving RowMapper as the parameter type e@nutabie public T queryForObject(strng sql, a RowNappercT> rowMapper, for query with enable params?) Object. ares) throws DateAccessException e@nultabie public T queryForObjectstring sal, for query with out w RowMapper rowMapperlthrows DataAccessException| — params (2) @Nullable public T> T queryForObjec(string sal, id ‘Object ars, for query with int aretypes, RowMapperct>rowMapper) throws DataaccessExcaption | Param lseme.s a) “The above methods must be called RowMapper() Impl cass bj as the argument valu econ ifjava method paramter type i an interface. we should cll method having impl class obj of ‘that interface as an argument value, ube student maczsting dat) ~>Method ets Student cls ob abays Persona > pli arson proces Sing data) > Method returns PErsonitssubassobh ue mpiyee COME ‘Tomake processdata] method returning any object randomly then we should take Object as return type public Object process(string data) [BAD > while calling we should go type casting, So theresa chance of getting ClassCestException) Student st-(Student)process}; cil inu oa sae! Employee emp={Employee) processt); To avoid type castings go for Generis based method designing public t _processStrng data, ClasseT> clazz}; . Type/Template Code is typesaten .qveryForObject("SELECT * FROM STUDENT WHERE SNO=2", crane Serer — Um aikntyrisomers toting, | See 0 sarge ne et fog " i : Hecters && getters ‘public StudentBO mapRow(ResultSet rs,int index}throws SQLException{ ‘[ [copy ResultSEt object record to StudentBO class obj tee a ss et i ae ee ae bo,setSaddlesgetstring 3); bo setavales.getFoat(t); return bo; , finer class Code Flow :: queryForObject) method gets the injected S from jlldbeTemplate obj) ~> Using that OS fgets one jdbc con object from je con poo! > Using that con object creates PreparedStatement bj hang given SQL query as the pre-compiled SQL query -> set given var args as query param values~> ‘executes the query and gets RS obj with one record-> calls s.next() method, gets retrieved record index from D8 table ~>takes second argument (StudentMapper obj->RewMapper obj) => ells mapRow;) on that object having RSrecord index as the argument values ->mapRowl--} copy RS object record to STudentBO cass obj and ‘returns that object queryForObject its caller (generally the DAO class method) instanceOt Is java operator to check wheather gen reference varable/objec Is pointing to certain type class object or not. it ratums boolean value. (true/false) {types inner classes 2)Normal inner class. [To use its logis in multiple non static methods outer clas) b)Nested inner clas/static inner class [To use its logis in multiple staticinon-static methods outer class] «local ner clas [To use its logles in a method definition in multiple method calls] 4) Anonymous inner class [To use its logs only in one method call] note::The methods of ldbcTemplate class will throw DataAccessException and its subclasses related Exceptions based on the problem that I rlsed. “Anonymous iner cass based logic while working with queryForObject(;) having RowMapper studentB0 bo=nul; bosit.queryForobject(GET_STUDENT.BY_NO, // are) [new RawMapper-StadentBo>(){ @overrde publi StudentBO mapRow ResultSet nt rownum) throws SQLException {| studentB0 bo=nul; bosnew Student60() bo.setSno(s.getint() bo.setsname(s.getsting 2); bo.setsada(s.getstrng(3); rel Ufmaprow() |__ ay/anonymous inner class //arg2 ao ars In arg2 total 3 things are happening {2} One anonymous(name les) inner class ‘createed implementing Row!apper!) {(b) mapRow',,) is implemented inside that ‘Anonymous inner cass (e) object created for anonymous inner ‘dass and passed it as second argument to.queryObject(-) method. LAMDA Expression based "Anonymous Inner cass based logic while working with queryForObject(-) having RowMapper Student80 boll, bolsf.queryForObject(GET_STUDENT.8Y.NO, / sre {te rownum} ot ‘Student80 bo=nal bbounew Student80(); org? bo.setSno(-getint)); LAMA based bosetSname('s.getstring(2);| Anonymous iner class bo.setsada(s.getstring(3)}; bosetAvg(s.getFoat()}; retum bo} Vimapiow'-, so //aes h ‘BeanPropertyRowMapper i pre-defined Impl class of RowMapper() having logic to copy RS object ‘record given Java Bean class object properties but RS object record db table col names and java Bean cass Property names must match. Student80 boll, bois. queryFOrObleet(GeT_sTUDENT.BY_NO, // agi new BeanPropertyRowMapper{StudentB0.class),//are2 no //are3 % ‘Working wit Resultsetextractor callback Interface = If SELECT SQL Query execution gives multiple records to process then go for ResullSetExtrator oF Rowcallbacktisndler ‘> The Best usecase Is geting LIst of 80 cass objects from RS after executing Select SQL query that ‘ives multiple record. wr query (string sql, Resulesetextractor re) Efeeafoa query given sate SOL eading the Reale with a ReslSetstractor. wr ry(string sal, Resultsetextractor ese, object... args) ‘Query given SQL to cente a prepared statement fam SQL anda tof arguments to bnd tothe query readin the ResultSet witha ResuStExteacto. mr ueryistring sql, object{] args, Resultsetextractor re) ‘Quer given SOL to ceato a propre statement from SOL and alist of arguments tobind tothe query, ren the ResultSet wth» ResitStEstractor, requlrememt:: AO class should gives bunch of records as Ust obs from Student D8 table based onthe given student addresses (sada) cityicity2.lty3 values. note:: RowMappercT>, ResultsetExtractor, RowCalbacktiandlerc> are functional interfaces becoz they are having ony one. ‘method declaration. directly or inrectl. ResutSetEutractor(!) [Callbackinteface) ‘According to the above [=> public extractData(Resultset throws SQLException [Callback method] | reir method we should tke ‘eDoas Ustestudent60> ‘Writing ResultSetExtractor())Impl class as Nessted iner lass in DAO class override public Ust getstudentsBYCiteystrng city, tring ciy2, String citys) { LUsteStudentB0> istBO=null listBO=ft.query(GET_STUDENTS_BY_CITIES, //argh ‘new Studentextractor), //ae2 cyacty2clty3 //args3 (var tgs) nested inner class static inner cass private stati class Studentextractor implements ResultSetExtractor>{ @ override Public Ust extractData(ResultSet throws SQLException, DataAccessException { UstestudentBO> tst8O=nul; Student@0 bo=null; Lcopy RS object records to List of StudentB0 collection ‘istB0=new ArrayList) while(s.next)) rs{Resultset) ‘Uget each record into studentB0 class object sor raja hyd 99.99 bbo=new StudentB0{); 02 rajesh vag 99.99 bbo.setSno(rs.getint()} 105 resures hyd 69.99 bo.setsname('s.getstring(2)); bbosetsadd(s.getsting(3); bo.etave(s.getFlost(4)); ‘Ufada each 80 class 0b to List clleciton listB0.adabo) Uywtite return istB0; MfextactDatal} LstcstudenoTO> Wiener class ResultsetExtractor!) mpl by using anonymous ner lass of DAO override Publi UsteStudentBO> getstudentsByCitesstrng city, tring ciy2, String citys) { UUrteStudent80> Ist 8O=null lietBonft.query(GET_STUDENTS_8Y CITES, //argi [row ResultSetEnractorctist>(){ override public UsteStudentBO> extractData(Resutset)throws SQLException( UsteStudent60> lit6=n Student@0 boll; Ueopy RS object records to List of Student80 collection {istBOmew Arrays; while. next(){ Inner class impldmenting get each record into Student80 class object Resultsetexacto|<1>I) bosnew studentB0(); bo.setsno(s.getnt()}; bo.setsname(s.gettring(2)) bo.setsadd(rs.getsting3)); bo.setavgls.getFloat() [Jad each BO clas ob to Ust collection letB0.adabo}; Westie return list60; loxatdata(-) 1, 1] anonymous inner class are oras | iysiy2sciyS //args3 (var aes) return ist80; Mimethod Public Ust getStudentsByCities string city, tring city2, String city) { Ustestudent80> Olona ‘itB01-f query GET. STUDENTS_BY_cES, //gret rot UstesudentB0> tstB0= Student80 bo=nl; Zeopy RS object records to Ustof StudentBO collection tstBOnnew array arg2-LAMDA ext on based while(rs.next()) { ‘Anonymous mer dfs for Tee each record nt Student 80 class obfect Resutsetexactr getstudentsByCitosstring city, tring city2, String citys) { UsteStudentBO> listB0=null BeanPropertyRowMapper borm=nul; /Tereate BeanPropertyRowMapper cass obj that hapl to copy each record into one BO cass obj bbprmsnew BeanPropertyRowMapper(StudentB0.class); lstBosjt.query(GET_STUDENTS_8Y CITES, //argh new RowQapperResultSetExtractr(bprm),//3 ty clty2cley3 //args (Var as) » return ist60; RowCalbackHandler callback method is: publi vod processRow(Resultset r)throws SQLException |-->itie stateful becoz Implementation class obj femembersthe state across the multiple executions of processRow() method. |-sin contrat to a ResutSetExtractor, a RowCallbackHandler objects typlcally stateful Itkeeps the result state within the object, to be avallable for later inspection. . Student80 obj ee ss{Resultset) aja hyd 90.66 = student80 obj oz rajesh vizag 47.66 102 rajesh vieag_ 47.66 103 suresh vinag 56.65 a TE RowCallbackHandl Implementation using nested inner class override public ListeStudentBO> getStudentsByCities1 (String city1, String city2, String city3) { ListstudentB0> st5O=new Arrays); |tquery(GET_STUDENTS._BY_CITIES, IRquery(s-r) gets injected Ds ~> gets con obj from DS ~> creates PS ew StadentCallbackHandler(lst8o), | ving given Query as pre-complled query ~>set ctyt/2/3 a the query pas, eiy.y2ty3); values executes Query and gets RS(main RS)-> In loop gets each earn i ‘record frm mainfS and creates seperate RS and calls procesow/(S) , 7 ‘method for mulipletimes.n the ProessUistBO is filedup BO obje ven by processRow(--] method. private static class. StudentcallbackHandler_ implements RowCallbackHandler{ private ListeStudent80>listB0; public StudentcallbackHandler(Uistist50) { thiststBOsIst80; ) @override public void processRow/(Resultset rs) throws SQLException { $ystem.out printin( “Student AOImpl-StudentCalbackHandler.processRowt}) Student0 bo=null [covert RS record into BO els object bo=new StudentB0(); bo.setSno(s.getint(1); bo.setsnamo(s.getstring 2); bo.setSadd(s.getstring(3); bosetAvg(rs.getFioat(§)); listB0.add(v0); Uimethod Winner cass ‘Anonymous mer class based RowCallbackHandl eovertide Public Lst getStudentsByChisd (tring cit, String city2, String city) LUsteStudentBO> istBO=new Arravllst(; Jtequery(GET_STUDENTS_8Y CITIES, ‘now RowCallbacktandler(){ @0verride public void processRow(Resultset rs) throws SQLException { ‘system. out println{ “studentDAoimpll.getStudentsByCites1(.).new RowCallbackHandler() (.).processRow()"); ‘Iiqet each record into Student class object ‘Student60 bo=new Student®0(): ‘bo=new Student80(); bo.setsnols.getine(2): bo.setsname(s-getstring 2); bo.setsadd(rs.getsting(3) bo.setAug(s-getFloat(4)); [ada each 60 class ob to Uist collecton 1stB0.add(b0}; y » itysetty2cty3)s return lit80; LAMA expression based Anonymous inner class implementation for RowCalbackHandlor-) @overtide public UstcStudent8O> getstudentsByChies String city, String city2, String city) LUsteStudentBO>lst6O=new ArrayList); J.query(GET_STUDENTS. BY CITIES =>{ ‘U1 4e% each record into StudentBO cass object ‘System out printn(’StudentDAOImpl2. getStudentsyChies1()..AMDA. Student60 bo=new Student601}; bbo.setSno(s.getint(a)); {ade each 80 class ob to List collecton list0.add(bo}; » ycity2ciy3 oturn list Resultsettxtractorl Rowcallbacktandler (I) (a) it stateless in nature becor there is no need (2) Tels stateful in nature becor It remembers of remebering state across the mutiple executions of ‘the given state lke list80 across the multiple executions Imp class object ‘ofthe Impl class object. {) exractData()is the callback method and it executes | (b) processRow:) is callback method and it executes for multiple times only for 1 time {elinvovles only one ResultSet object in the entire process | (c} Involves multiple RS Objects (n¢1) inthe entire process n> records count glven by "SELECT SQL Query" {4 Good in pertormence (4) bad in performence {} Support for Generics {) Nosupport for Generics (f) we have multiple useful eadymade impl classes (9) weddo no have here NamedParameteridbeTemplate ‘= It is given to support named parameters in the SQL query. => The Limitation with positional params (2) fe providing index and setting values to those parameters according tothe index i bit complex. especialy ifthe query having ‘multiple positional parametes ‘To overcome the above problem use named parameters () which gives name to each ‘rameter and we can st values to parameters by specifying thelr name, {query with postional params SELECT EMPNO,EMAMEJOB,SAL FROM EMP WHERE EMPNO>s? AND EMPNO?_ 3 2 {query with named params SELECT EMPNO,EMAME.JOB,SAL FROM EMP WHERE EMPNO> in AND EMPNOcs "Named Parameter rote: JdbeTemplate does not support Named Parameters. t supports only Positional parameters ‘note: NamedParameteriabcTemplate supports named Parameters but does not support positional parameters. ‘This class delegates to a wrapped JabcTemplate once the substitution from named parameters to JDBC style "placeholders {done at execution ime. It ale allows for expanding ast of values to the appropriate number of placeholders ‘NamedParameteridbeTemplate obj 4 late obj NamedarameterldbcTemplate object has IdbcTemplate object Le composition (Has-A Relation) ‘We can set value NamedParameters in 2 ways while ‘working with NamedParameteridbcTemplate Using Mapesuing Objec> obj “here the named parameter names are keys and param values are values 3) Using SlParametersoure() implementations i) MapselParametersoure (c) |->use its addvaluel) method having param name, param value asthe arguments ‘peanbroperyalParameter Source (c) |->Alows Set JavaBean obj values asthe named parameter values but the ames of named parameters and the names java bean das properties must match ‘>To create NamedParameteridbcTemplate we need DS object a the dependent object =>NamedParameteridbcTemplate alo glves support to work with callback interfaces. “>NamedParamers are case-sensitive. example code EmployeeDAoimpliava ‘package com.nt.da0; Import java.ut.arraylist; import java.util. Import java.util.Map; Import orgspring framework beans factory annotation Autowired: Import org springframework jb.core.namedparam. BeanPropertySqlParameterSource; Import org. pring framework jdbe.core.namedparam, MapSqlParameterSource; Import org. pring framework jab. core.namedparam, NamedParameteridbcTemplate; Import org springframework stereotype-Repository; Import com.nt.bo.Employee80; @Repository("empDA0") public class Employee AOImp! implements EmployeeDAO { rivate static final String, GET_EMPNAME_BY_NO»"SELECT ENAME FROM EMP WHERE EMPNO=:n0"; Private static inal String, GET_EMPDETAILS_6Y_DESGS="SELECT EMPNO,ENAMEJOB SAL FROM EMP WHERE JOB IN:desgl,:desg?,desg3)" private stati inal Sting INSERT_EMPLOYEE="iNSERT INTO EMP(EMPNO,ENAME,JOB,SAL) VALUES(-empto,:ename,job, sl) @autowired private NamedParameteridbcTemplate npt; @override publi String getenameByotint no) { (/*Mapestring Objec> paramMapenew HashMap(); parambap.put("n0",no};*/ "MapcString Object» paramMap=Map.of("n0"sno); //javas feature ‘ting name=npht.queryForObject{GET_EMPNAME_E No, Strings: return name: Vimethod @override public Ust gotEmpDetallsByDesgs(string desg, String desg2, String desg3) { TTrepare MapSqiParamete/Source obj having the pamesvalues of he named pa ‘MapSalParametersource mspe-new MapSqlParameterSource(); ‘mspsaddValue( "dese" desg1); //namedparam, value LUstcEmployeet8O>lst8O=npt.quary{GET_EMPDETAIS_BY_DESGS, rot LUstcEmployee0> lstBOtenew ArrayList); whites. next() { ‘EmployeeBO bo=new EmployeeBO(); bo.setEmpNo(r.getint(2)}; bo seténamelregetstring(2); bo.setlob(s.gtString(3); bo.setsalfrs.getloat()}; istBO1.ad(b0); uiwite return IstB01; My return IistB0; Mfmetiod @override public int nsertemployeelEmployeeB0 bo) { {nt count=npitupdate(INSERT_EMPLOYEE, bps}: return count; ielass SimplelabcTemplate ‘=>Introducedin spring 2xas alternate to idbecTemplate supporting new features of that timelike generics, var args and et. ‘>continued and deprecated in spring 3.x becor they upgraded JdbcTemplate itself supporting features like generics var args and et.. ‘>In Spring 44 the SimpleldbcTemplate is removed. Simpleldbcnsert Sapproaches of writing loge in spring jdbe 2 Using dbeTempate {A Simpleldbcnsertis a mut threaded, reusable object providing easy insert 1) Using NamedParameteridbcTemplate capebilities fora table I provides meta-data processing to simply the code €) Using SimplesdbetabeTempate needed to constructa basic insert query. Allyouneed to provides thename _¢)Using SimpleidbcinsertsimpleldbeCall lof the table and a Map containing the column names and the column values. ) Mapping SOL Operations as sub classes. JddbcTemplate,NamedParameteridbcTemplate, SimpleldbeTemplate are threadsafe Le they are ‘single threaded objects. so they allow only one thread at time to perform persistence operation ‘they are not suitable multithreaded time critical web applicaiton env...ike online auction/bidding and online Counselling, online shopping and etc. ‘=> In the above situations, we can use “Simpleddocinser" for insert persistence operations. becoz itis ‘multithreaded... multiple threads can be perform insert operation simultaenousy.. ‘=> While woking with "Simpleldbcinsert" we do not write INSERT SQL Query” Seperately..we ust provide 1S, Dbtable name, Map of Col names, values... then insert SQL Query willbe generated dynamically Simpleldbetnsert 1-305 (os dopesannt sal] ‘The actual inset is being handled using Spring's JabcTemplate. [->setTablet-) |—sint execute(Map mep) (on) takes colnames and col values. int execute(SqlParameterSource source) |->MapSqlParameterSource (¢) ~SusingaddValuel,] we need to pass col names and col values |->BeanPropertysaiParameterSourcele) ~sHere we can pass JavaBean object as input for col names and colvalues..but db table cl names and Java Bean property hemes must match. {) simplelébcinsert Internally uses JdbcTemplate for completing generated insert SQL query execution ‘then how can say its multi-threaded as we know ldbcTemplate is sngleThreaded? Ans) ifwe call execute) method on Simpleldbcnsert for multiple times..then multiple JdbcTemplate clas objects will be used internally to execute the generated Insert SQL. query for multiple times, So the Simple/dbelnsert becomes multi- threaded. ‘Q)Why Spring JO8Cis not providing “simpleldbcUpdate*, “simpleldbcDelete" and "simpleldbcSelect” classes? ‘Ans) update, delete and select SQL queries execution takes place along with conditions .. Based on ‘siven table name, col names and col values. these conditions can not be generated dynemically.So “There are no "SimpleldbcUpdate”,"SimpleldbcDelete,"SimpleldbcSelect” classes. note: Insert SQL query executes with out any condition ie It can be generated dynamically based on the given Db table name, col names, col viaues..So "simpleldbcinsert” is given.. A Howto execute update, delete select SAL queries in multithreaded env..? ‘Ans)simplesdbccall multi-threaded object having ability to call PL/SQL procedures or functions So keep ur update, delete select SQL queries inside PL/SQL procedure or functions and call them, by using simpleldbeCall object. Q)willsimplejdbcinsert support postional/named parameters? Since programmer is not preparing query « and query is generated dynamically. So ‘there is no posibilty placing of any kind of parameters. Example Code @Repostey("bankOAO") public lass BankaccountD AOI! Implements BankAccountDA0 { @Autowired private Simplelebensert se overnite public in rogbterSarkAccount80 bo) { “Terepare Map objet having col names and vale [Map mapsap.ft'aco", vo. getAcno(), “holdenvame’, a ‘o.getHolderntame!) "balance bo.getalance(), status getstats)}; //Jave9 feature SlesetTableNeme( BANK ACCOUNT" ZToxseite query by gener Ayame fot counts anacutaina: > eat » 1 aml bean “ean ide MOS" clste'cm zoster ik ikefDataSoure™> “property name" diverClatome" value= oroce be diver. OraceDiver/> “property narne= "minimum" value="10"/> <-€ft Simpletdbensere-> ‘constructors ree"hkas'/> content component.scon base packages"omnt.doo"/> O) then Resi TESTA SQL developer —> Procedures —> right click > ise new Procedure —> RESULT: INVALID CREDENTIALS END IF; END P_AUTHENTICATION; simplesdbecalt |-50s (required a: dependent obj) |->setProcedureName(-) [To specify PL/SQL procedure name] |->setFunction(true/false) [ set to true . if the above name is PL/SQL function name otherwise set to fal |->Map execute(Map inparams) a To supply param names andl cay pi/sat proc names and values values as Map object aetap obj (dearutt) [MapsString.Object> execute(SqlParameterSource source) ‘TeT> executoFunction(Class returnType, MapeString,?> inParams) ‘To-call PL/SQL function, [> Tet> executeFunction|Class returnType, SqlParameterSource inParams}) example code @Repository(“authOAo") public class AuthenticationDAOImpl implements lAuthenticationDAO { ‘@Autowired private Simplesdbecall sic; @override public String authentication(String user, String pw) { /iset procedure name sjesetProcedureName("P_AUTHENTICATION"); prepare Map of IN Params ‘MapeSting,2> inParams=Map.of{"USERNAME" user,"PASSWORD" pwd); //java 9 feature Healt PL/SQL. procedur ‘MapeString,2> oy:Paramensic.execute(inPargms); inParams (Map obj) etum (String) oftParams.get(™RESULT), VALID CREGENTIALS key value ‘Approucs Mapping SOL Opeatonsuers} at sub cases ag Salaury

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.yml What 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 “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.)

You might also like