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

Hibernate PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
117 views

Hibernate PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 177
Hibernate pre-requisites :: Core java + basic of JDBC + Basics of SQL + lots of common sense Only Spring learning is great .. but learning spring with hibernate is super super great. To learn and to use Spring ORM , spring Data Jpa modules we need Hibernate knowledge a lot Here we are going learn both Hibernate and JPA > Hibernate 4.x /5.x and intro to 6.x duration :: 75 to 85 Sessions ( 6/7 days in a week) =>12+ tools will be covered as common topi ike log4j, maven,gradle, svn,git and etc... =>Course fee : 2000 ‘Admin person details :: Mr. srikanth phone :: 6302968665 => Fb Group :: natarazjavaarena (https://www.facebook.com/groups/natarazjavaarena) =>dialy 1.35 to 1.45 mins.. email id :: [email protected] => BatchCode :; NTHB915 Uccan learn Spring ,hiberante, Adv.java courses parellel. What is PErsistence? The process of storing and managing data for long time is called persistence... We use support of SEcond memory devices like HDD, CD,DVD , Thumb drives and etc.. for persistence... => Storing data in the Application variables ,objects does not come under persistence..becoz they allocate memory in the RAM that to only during the Application execution... Once the execution is over .. they will be vanished. So data can not be used across the multiple executions of same App or diff Apps... =>To overcome the above problem take the support persistnece ie write application data (both inputs and outputs) to Secondary Memory Devices like HDD and etc.. with the support of files and DB s/w... Important terminologies a) Peristence store b) PersistentData c) PErsistence operations d) Persistence logic (e) Persistnece technology /Framework/Tool Persistence Store Itis the place or store where data will be saved and managed for long time jes_, DB s/ws (oracle, mysql,postgreSQL....) eg: Persistent Data ‘The Data of Persistence store is called PErsistent Data... eg: file info , DB tables and their records Persistence operations insert,update,delete and select operations performed on Persistent Data .. => These are also called as CURD/CRUD/SCUD operations. CURD/CRUD scuD C->create (insert) U->Update (modify) oes R —>Read (select) o-2creuta U->Update D~>Delete (remove) oe liane Persistence logic => The logic that is written to perform CURD/CRUD/SCUD operations. eg: lo stream logics (like serialization ,DeSerialization), jdbc code hibernate code, spring jdbc code, spring orm code, spring data code (hot cake) and etc.. java learning |-—> language (Core Java) |-—>Technologies (adv java) |-—>frameworks (spring, hibernate, ...) Persistence Technology/Framework > The technology /framework/tool using which we develop persistence logics JDBC (Technology) hibernate ( framework /Tool) spring jdbc/Spring ORM/Spring Data ( framework) =>Persistnece Technology/framework /Tool is given for developing persistence loiges to perform Persistence oeperations on the persistent data of persistence stores... Data Storage Techonologies/softwares Vs DataAcessTechnologies/frameworks The s/w which store and manage data is called Data storage software eg: Db s/w (oracle,mysql and etc..) The s/ws using which we can access and manipulate the data of DataStorage software is called Data Access Technology/framework/software eg: jdbc , hibernate, spring jdbc and etc... Java app —> Flat Files (like serialization , Deserialization) (The file that nutral to all OSs, languages) (text file, xml fies..) Java App RDBMS DB s/w (oracle ,nysql and etc...) 0008s /w Pr ee > ODB s/w ( wakanda , Object Store ,ODABA and etc..) (Object Data base softwares) Limitations with flat files as persistence stores (a) No Security (b) No constraints (c) No Sal support | 102 ramedh hyd me pee] (d) getting data with multiple conditions is very complex (e) performing update and delete operations is very complex (f) No realationships @ (g) Merging and comparision of data is very complex... To solve these use DB s/ws like RDBMS,ODB s/ws... 103 jnai delhi slerk } note:: We generally use Files as PErsistence stores only in Memory Critical Apps like mobile Apps, mobile games, Desktop games and etc... ODB s/ws or OODB s/ws These Db s/w can store software objects directly in Db s/ws as column values... and so useful while working OOPs languages becoz in OOP we get every thing as objects... public class Student{ private int sno; private String snami Student st=new Student(101,"raja","hyd" 56.551); private String sadd; Studantelass obj privat float avg; H/eetters && Setters (methods) — \ } <== DDE s/w of OODBS: Student (db table) details pros of ODB or OODB s/ws => In Object oriented PRogramming we get objects every where and we store them directly in Db s/w Le there Is no need converting simple values to objects and objects to simple valeus while doing persistence operations => Al CURD opeations can be d on the objects =>No need of SQL .. We can these Db s/w as NOSQL Db s/w.. employee.txt 101 raja hyd clerk 103 jani delhi clerk cons of ODB s/ws or OODB s/ws Does not allows keep data/objects in relationships. => The language in which u r creating software object should have compitability with ODB s/w. (There is tight coupling b/w Object oriented Db s/w and the language in which the software objects are created) => Against of Normalization rule1/form1 (Do not store multiple values in single col. Always store multiple values in multiple cols) => These are not industry standard Db s/ws ... Different types of DB s/ws and etc... (a) HDBMS Db s/ws (hierarchal DBMS) (b) NDBMS DB s/ws (Network DBMS) (c) RDBMS Db s/ws (Relational DBMS) (d) OODBMS DB s/ws ( Object Oriented DBMS ) => People had not shown any intreset on ODB s/w becoz of RDBMS DB s/ws popularity. and more over they are very much habituated with RDBMS Db s/w like oracle,mysql and etc... (like hibernate) jdbc, o-r mapping Java App > RDBMS Db s/w (oracle , mysql, postgre SQL and etc..) itations of JDBC to develop Persistence logic (a) We develop JDBC Pe ‘ence logic using SQL Queries .. Since SQL Queries are DB s/w Dependent Queries we can say JDBC PErsistence logic is DB s/w depenent PErsistence logic and JDBC Code /persistence logic is not portable across the multiple DB s/ws.. note:: changing DB s/w in the middle of development or production or after development and before release is very complex.. (b) spBc Persistnece logic /code is having boilterplate code problem.. jdlbe oat The code that repeates in multiple parts of jdbc code in Java App App/Project either with no changes or with minor changes is called boilerplate code. => Load jdbc driver class to activate JDBC driver s/w => Establish the connection with Db s/w onmeniags => create Statement object => Send and execute SQL Queryin DBs/w — Application specific logics. => Gather results and process the results... =>Handle the exceptions common logics => close jdbc objs including jdbc connection ==> comming logics are nothing boilerplate code... (c)_ JDBC Code throws SQLException which is checked exception... |—>To Mandatory to handle. class |--> Exception propagation to next class/caller is not possible if we catch and handle the exception. public void m1(}{ try{ =>UnChecked exceptions are good becoz they , are optional to catch and handle _, they support Hfidbc exceptin propagration by default. catch(Exception e){ } } (d) In JDBC, for all problems we have Single SQLException class... i.e we do not Detailed Exception Classes for Different Problems. (e) Whilse closing jdbc objs including jdbc connection obj we need to analyze a alot... ~>closing jdbc objs at the end of try block (or) in the catch blocks or in both places is bad practice.. closing in finally block is good pratice /[idbe code i catch... catch(—}{ finally (finally try tryf if(rs!=null) rs.close(); Daft code. rs.close(]; _Ggod pratice st.close(); °°} Fosi oa tolclose jdbc objs con.close(); WHE BHeFdbe obj, if catch(ou){ .«} ” exgeption raised aa catch(..}{.} th control goes catch Siestcmua bidck and we are not } : : st.close(); | giving fair chance to ‘ foe other jdbe objs oP tryf if(con!=null) con.close(); catch(...){ 4} finally /Jif we use try with resource for jdbc code , the jdbc objs will be closed automatically at the end of try i.e we need not to close them manually .. using finally block.. try(Connection con=DriverManagr.getConnection(-,-)}{ try(Statement st=con.createStatement()){ try(ResultSet rs=st.excuteQuery("SELECT * FROM STUDENT"){ w» /flogic to process the ResultSet object itry3 note:: doing TxMgmt by calling con.commit() , Witry2 con.rollback() is bit Vitry1 complex in try with resource. catch(v.){ sn} catch(....] {ou} f) JDBC ResultSet objs are not Serializable objs i.e we can not send their data them over the network directly... ie we need convert ResultSet records to other values in order to send them over the network.. note: The process converting obj's data into bits and bytes is called serialization. So these bits and bytes can be sent over the network or to file.. Serizlization is possible only on serializable objs nothing but the objs whose classes are implementing java.io Serializable(!) 8) Java is object oriented programming language. but we can not use objects directly in jdbc persistence logic i.e we need to convert objects data into simple values in order use them in SQL queries as inputs becoz SQL queries can not take java objects directly as input values.. public class Student{ jdbc code private int sno; iB Student st=new Student(101,"raj hyd"); private Stringeadd: va") //3 param constructor PreparedStatement ps= con. prepare Statement("INSERT INTO STUDENT VALUES(?, /Ieetters & getters int no=st.getSno() ; String name=st.getSname(); String addrs=st.getSadd(); ps.setint(1,no); ps.setString(2,name);_ ps.setString(3,@ddrs); Here "st" object data is converted into simple values... in order use in jdbc code... h) There is no proper Transaction Management support =>The process com! related operations into single unit and executing them by applying do everything or nothing principle is called Transaction Managment. eg: trasnfermoeny with withdraw, deposite operation Student registrion with inserting record to student db table and inserting record to course db table. two type Transaction Managmenents {a) Local Transaction Management -—> HEre all operations take place on single DB s/w eg: transfer Money operation b/w two accounts of same bank. (b) Global Transaction Management --> Here different operations take place on different DB s/ws.. ransfer money operation b/w two accounts of two diff DB s/ws.. note: In jdbc there is good support Local Tx mgmt , But there is no proper support for Global Tx mgmt i) JDBC supports only postional parameters (?) in the SQL query .. and it does not named parameters... (name for each parameter) : syntax of named parameter 2) postional params insert into student values(:no,:name:,:addrs,:age,:avg,:m1,:m2,:m3) insert into student values ( named parameter, j) Strong SQL knowledge is required to work with JDBC code... k) while developing persistence logics in JDBC we can not enjoy inheritence, polymorphism composition and etc.. features oops becoz jdbc does not allows to objs as input values in the SQL queries... 1) JDBC does not supporting versioning and timestamp features as bult-in features. i we need to write lots lines of code to implement those features. Versioning :: keeps track of how many times the record is mo timestampin; ed. keeps track of when record is inserted and lastly modified (date,time) and etc... =>To solve most of these problems ... prefer writing persistence logic using o-r mapping env.. taking support hibernate, ibatis , toplink ,eclipse link and etc.. ORM frameworks /Toos.. note :: spring ORM , Spring data interally uses one or another ORM framework... What is o-r mapping? Short anwser ::It is all about mapping /linking classes with Db tables Lengthy Answer :: The process of mapping java classes with DB tables , member variables of java classes with columns of DB tables and representing the records of DB tables with the objets of java classes having synchronization b/w them is called O-r mapping... ==>Here the word synchronization is used having english meaning... le the modifications done in Objects will reflect to DB table records and vice-versa. Studentjava (Entity class/PErsistence class/Model class/Domain class) package com.nt.entity; o-r mapping cfgs (xml annotations) What is Configuration? public-cless Student Student (java class) <---> Student_Tab (db table) private int sno; ~~ > Providing info about about various comps like private String sname; files/classes /code to underlying server/cotnainer/ private String sadd; a eee jvm/framework and etc.. to give instructions is private float avg; called configuration. //settters && getters note1:: java class will be treated as servlet comp and linking with url based on its configuration done & 4 getters DB s/w in web.xml file... or using annotations.. setters => Java class becomes Hibernate entity class and will be mapped with DB table based its configuration done hibernate cfg related xml file or using annotations. JAva App (o-r mapping Persistence logic) Here we can perform all persistence operations through objects by persistence instructions to ORM framework like Hibernate in the form of objects with out using anySQL Queries This makes o-r mapping persistnce logic Db s/w independent persistnce logic. But the ORM framework like hibernate internally uses JDBC code +SQL Query to complete the Persistence operations. In O-rMapping Persistence logic development , the objects of Entity classes like are actors playing different characters. note: After deleting record represented by object... the object will not be deleted more over we can use that object for other persitence operations on different records of same table. o-r mapping Saving object means writing object data to db table as record updating object means modifying the db table record represented by the object Loading object means selecting the record into the object from the DB table Deleting object means deleting the record represented by the object... There are multiple frameworks/Tools/Technologies to develop o-r mapping persistece logics they are called ORM framework/toos/Technologies EJB Entity Bean (Technology) ~ from Sun (oracle corp) (outdated) Hibernate (Tool/Framework ) SoftTree /Jboss/RedHat (1) iBatis — > fromapache {3} All java based ORM frameworks are given Toplink - satenietnale pet based on JPA specification rules and guidelines En pee JPA —->Java Persitence API 1B - open JPA >from Sun Ms/Oracle corp and etc.. JPA(JAva PErsi API) (Techolagy/Specification) ives rules and guidelines to ORM E/w] 4 i Hibernate (ORM Framework) RM frameworl) (Oracle corp) What is o-r mapping? Short anwser :: It is all about mapping /linking classes with Db tables Lengthy Answer :: The process of mapping java classes with DB tables , member variables of java classes with columns of DB tables and representing the records of DB tables with the objets of java classes having synchronization b/w them is called O-r mapping... ==>Here the word synchronization Is used having english meaning ... Le the modifications done in Objects will reflect to DB table records and vice-versa. Student.java (Entity class/PErsistence class/Model class/Domain class) package com.nt.entity; public class Student{ private int sno; o-r mapping cfgs (xml annotations) What is Configuration? Student (java class) <---> Student_Tab (db thble) Py . Kano <—>itno {| > Providing info about about various comps like private String sname; java lass shame <-->stname| (Db table files/classes /code to underlying server/cotnainer/ private String sadd; propertiqs oud <-> stadd cols) jvm/framework and etc.. to give instructions is print oa: ve = avg <—>stave _| called configuration. java class will be treated as servlet comp Awatters and linking with url based on its configuration done & A getters DB s/w in web.xml file.. or using annotations. -> Java class becomes Hibernate entity "8 class and will be mapped with DB table 90.55 based its configuration done hibernate cfg related xmI file or using annotations. JAva App (o-r mapping Persistence logic) st1(Student object) a raja_/hyd king ~ ramesh Here we can perform all persistence operations through objects by persistence instructions to ORM framework like Hibernate in the form of objects with out using anySQL Queries This makes o-r mapping persistnce logic Db s/w independent persistnce logic.. But the ORM framework like hibernate internally uses JDBC code +SQL Query to complete the Persistence operations. In O-rMapping Persistence logic development, the objects of Entity classes like are actors playing different characters... note: After deleting record representted by object.. the object will not be deleted more over we can use that object for other persitence operations on different records of same table. o-r mapping Saving object means writing object data to db table as record updating object means modifying the db table record represented by the object Loading object means selecting the record into the object from the DB table Deleting object means deleting the record represented by the object... There are multiple frameworks/Tools/Technologies to develop o-r mapping persistece logics they are called ORM framework/toos/Technologies EJB Entity Beart (Technology) -- Hibernate (Tool/Framework ) —~ Batis Toplink Eclipse link oO - open JPA -~ and etc. -->from Sun (oracle corp) (outdated) > SoftTree /Jboss/RedHat (1), > frominpacher(3) All java based ORM frameworks are given -> from oracle copr based on JPA specification rules and guidelines JPA --->Java Persitence API use When to use JDBC and when to Hibernate(ORM Framework/Tool)? Offline App :: The app that runs with out human intervention (or) enduser interaction eg:: census Application ( Population count) School teacher —--> home ——-> gathers details on paper —> submits to mandal/taluka head quaters —-> DEOs converts info to Excel sheets —> sheets uploaded central GOVT App —> takes excel sheets —-> validates them, corrects them , categorizem and stores in to Db s/w.. Online App :: The app that runs with human intervention (or) enduser interaction eg: flipkart.com, amazon.com, nareshit.com and etc... =>Online or offline Apps when they are getting huge amount of data batch by batch for processing then use JDBC .. becoz it creates single ResultSet object to maintain huge amount of records. if we use hibernate here huge no.of objects will be created to represent and process huge amount of records then Project may crash. eg:: Census App ,Flipkart App ==>Online or offline Apps if we are getting little amount of data to process at a time then go for hiberante.. (ORM framework) becoz to represent small amount of records small no.of objects are sufficient and more ever we can get benifit of other features of ORM frameworks like DB portability and Time stamping , versioning, caching and etc... eg:: nareshit.com note:: youtube data , Google data, fb data and etc.. are BigData.. they are beyond storing and processing capacity of DB s/w... So go for BigData frameorks like Hadoop ,spark anetc... O oO A enduser/ Developer enduser/ Developer ORM framework (Hibernate) Spring ORM/Data (spring module) [ORM Framework (hiberante,iBatis,OJB and etc..) spec {Technolog} coclusion: Instead ing plain jdbc ,prefer using spring jdbc that allows us to devleope jdbc style SQL Queries based DB s/w dependent Persistence logic by avoiding boilerplate code of jdbc. spring jdbc needs plain jdbc knowledge... => Instead of using plain ORM frameworks/Tools like hbiernate prefere using Spring ORM to develop Objects based Db s/w independent Persistence logic with out SQL Queries. This also avoid boiler plate code relaed plain ORM framework programming. spring ORM needs plain ORM tool/framework) like hibernate knowledge... => Instead using Spring JDBC, Spring ORM use spring Data which takes care of both commons logics (boilerplate code) and regularly used Application specific logics (nothing but CURD operations persistence logic) Spring DAta sub modules —Seiiig ein JDBC --> generates common logics and specific logics by using [SQL DB) jdbc internally (so jdbc knowledge is required here) ~>Spring Data JPA --> generates common logics and specific logics by using (SQL DB) ORM framework (hibernate) internally . (so hibernate knowledge is required here) =>spring Data MongoDB (NoSQL DB) —> generates common logics and specifics required for interacting with MongoDB s/w. =>Spring Data Neodj =>spring DAta Cassendra DB s/w and ete. SQL Db | SaLObsiw. (Structured Data) {oracle,m@sql,postgreSQl and etc..) No SQL DB.s/w natarazjavaarena —->FB group (Unstructured Data) : 5 (MongéDB , Cassendra , neodj and etc..) [email protected] How to choose Data storage Technology and DataAccess Technology in Java ? (Persistence technology/framework/tool) Scenario1 (kb) =>App is small scale App and generating little amount of text data to persit PErsistnece store :: files eg: Mobile Games, Mobile Apps, Pesistence logicenv:: 10 Streams Desktop Games Java App , (little data (kbs) Scenario2 App is small scale App and generating objects based data to_ persist. Persistence store :: File Persistence logic env. 10 Stream (serialization and Deserilization) Scenario3: App is medium scale App like web application and generating medium sized — data .. (MB/GB) to persist as text data... Earenanediticonn pesistence store :: RDBMS DB s/w matrimony websites Persitence logic env :: jdbc /spring jdbc /spring data jdbc Java App/ web application jdbc /spring jdbc/ App is medium scale App like web application and generating medium sized (MB/GB) objects data based Data .. to persist Persitence store :: RDBMS Db s/w Peristence logic env :: ORM Framwork(Hibernate)/ Spring ORM/Spring Data jpa spicing data jpa App is enterprise App (complex App )/ Distrbuted App (App having different types remote clients) generating large amounts data (GB/TB) of data to persist in the form of text data.. or object Data These are complex app and also otisstoce store: RDBMS Obs) allows requests from diff types of remote Perescnes pipers: Jcfoprng be/oprig dnt dbe|eest ata, | lente: lke Andintd MobilaBnp; 15 mabile fibeidete/Surkag OnNA/Spring Gata joa App,browser Ul(html,Css) and etc.. So these are called distrobuted Apps or enterprise Apps. p Amazon.com flipkart.com Scenario6 Application is medium scale or largeScale App ( web application or _ enterprise App /Distributed App) generating unstructured Data .. to persist... :: NO SQL Db s/wis like MongoDB Persistnece env :: use specific NO DB apis or spring data NOSQL module > note:: Unstructured Data means .. The data that changes dynamically some times 4 values , some times 10 values , some times 30 values.. for same employee type details Java web application/enterprise App/Distributed App Data is huge amount of text data that is beyong processing and storage capacity given large scale Distributed or enterprise Apps having PB/XB/YB and etc.. to persist .. eg:: fb data google data, youtube.data.. PB ->peta bytes XB ->Xenota bytes Persistence store :: BigData framework(Hadoop/spark) —_ yg sYotta byte PErsistence logic env :: BigData frameworks (...) Employee Info a and te.. images\raja.jpg resumes\raja.doc SQL DB ,NOSQLDB ,BigData softwares do not store audio, video ,images files directly in records., just they maintain their locations as text data... natarazjavaare na --->FB group natarazjavaare, [email protected] =>Instead of placing multiple logics in a single file /class .. it recomanded to place in multiple layers A layer is logical partiation of the application that represents specific logics... ALayer can be one or more classes/files representing Cetatains logics.. eg:: Persistnece Layer/Data Access Layer , Service Layer /Business Layer ,presentation layer , Integration layer and etc.. => Advatanages of layered Application development (a) Multiple logics Il be placed in multi je layers ,, This gives clean seperation b/w logics.. (b) The modifications done in one layer logics does not effect other layers. (c) Maintence and Enhancement of the Project becomes easy. (d) Parelle! devleopment is possible , So the productivity is good (doing more work in less time with out comprimising in quality gives good productivity) | The main logic of App that deals with calcuations> (e) Itis industry standard analyzation is called B.logic/Service Logic and etc.. a = Se =>CURD Operations on Persistence store are called ~ ~>-Persistence logic =>MVC Architecture is very popular to develope layered Applications in java... Gives blueprint or plan or design to develope the applications,, M——— ---->Model Layer ( service/business layer (B.logic) + PErsistence Layer(Persistence logi |-—-> represents Data... DAO layer -—> view Layer —-> represents PResentation logic —> Itis like beautician ) -—> Itis like Accounts officer oom -->Controller Layer -—-> represents Monitoring/Controlling logic —-> It is super viser MVC is industry's defacto standard to develop java based Layerd Applications. Combination of various Technologies /framewroks of java to develop MVC Applications _ .. lidbe) ———> Java class with java bean > DB s/w (M) (b.logic & Persistence logic) (v) (c) ——> service class — (m—>b.logic) m= pesistence logic OR isp -—-——— > servlet -—-——-— —> EJB session Bean —-———-- > EJB Entity Bean (vy) (d M-—> blogic M-->Persistence logic ‘ (ORM), -—---> EJB Session Bean ~ —---—-> EJB entity Bean — > DB s/w M-—> blogic M->persistence logic (idbc} Struts -——->EJB Session Bean ———————- > DAO class (java class) > Db s/w Ww) (d) M-—>b.logic M-—>persistence logic Struts EJB SessionBean —> Hibernate (ORM) —> Db s/w Struts ———— ——> spring Core +spring AOP — (v) (c) M-—> Persistence logic flipkart.com Spring MVC — ——> spring Core + spring AOP_ -—-> spring jdbc/spring ORM/Spring data—> Db s/w wo M3 blogs /hibernate M-—> Persistence logic ‘Spfing Rest) External Services / Ditributed Comp/Service WebService (SOAP/Rpst) Different technologies /frameworks to develop Persisnce logics JDBC Hibernate + Toplink EclipseLink « JDO spring jdbc « spring orm + spring data + Batis EJB entity Beans and etc.. Different Technologies and fremworks to develope service logics/b.logics java classes spring core , spring JEE, springAOP * EJB SEssion Beans and etc. Different Technologies and frameworks to develop Exsternal services/ Distributed Comps RMI EB CORBA (outdated) WebSerivce (latest) * SOAP :: Simple object Access Protocol SOAP based WebSet (very less used) jacrpe jacws axis * apache cxf and etc.. REStfull webservices _jax-rs (metro) spring rest (good) + rest easy jersy Different Technologies to devleop controller Servlet * Servlet Filter Differente technogies /tools to devieop view comps css * ->bootstrap ~>java script -> angularjs ->angular + ->volocity ->themelfy ~>ajax -> Reactjs * -> jquery and etc.. diff frameworks to devleope w and controller logics togather Spring MVC (*) Struts JSF ADF natarazjavaarena —>FB group Webwork and etc. Hibernate type :: Java ORM framework/Tool or Implementation s/w of JPA Specification Vendor oftTree / RedHat / JbossVendor DRA idAvaRersistnecesAP) (Adivision of RedHat) version :: 6.x (under development) (compitable with java8 or 11) 5.x--> 5.4.18 (stable version) (compitable with java 8 or 11) (|->Developed based on jpa2.2 to specification) UAW based 'leneieazes are creator :: Mr. Gavin king scala, groovy ,kotlin ,java and etc.. Open Source To download s/w :: download as zip file from www.hibernate.org website... https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.4.18.Final/hibernate- release-5.4.18.Final.zip/download reference Books :: Persistnece with Hibernate by Gavinking ~->Hidernate supplied ref docs +api docs + class room content... To install s/w :: Extact zip file (hibernate-release-5.4.18.Final.zip) =>use \changelog.txt file to know which version is released in which year.. => \documentation folder gives api docs and ref docs... =>\lib folder gives _ libraries (jars ) =>\project folder gives -> source code -> sample Apps, projects and etc... Defination: snon-invasive Hibernate is an open source light weight , Portable and integrated Java based ORM framework or Tool that is given based on JPA Sepcification rules and guidelines to develope objects based o-r mapping persistence logics. open source =>along with hibernate installation we get its source code.. and more over hibernate frramework free s/w .. This hibernate as an Open source framework. makes Light weigtht Hibernate is ligtht weight becoz (a) Hibernate f/w Is given as zip file having less size (In mbs) (b) To develope and execute Hibernate Persistence logic we just need JDK/JVM and hibernate libraries(jars) , i.e there is no need of arranging the heavy weight servers / containers Portable Using hibernate we can develop persistence logic as objects based persistence logic with out using any SQL Queries support. This makes hibernate persistence logics DB s/w indepedent persistece logics and also portable across the multiple DB s/ws... note:: This feature helps to change the DB s/w in the middle of the development and also in the middle of the production. What is the difference b/w inavise programming and non-invasive programming? invasive Programming HEre the classes of App development are tightly coupled with underlying framerwork/ Technology apis... the App classes should implement /extend from underlying framework /Technology api interfaces/classes.. =>Here we can not move App classes to other frameworks /technology for execution... eg: struts 1.x (framework) ,Serviet (Technology) non-invasive Programming HEre the calsses of App development are loosely coupled with underlying framework/ Technology apis ie. App classes do not implement/extend from underlying framework or Technology api interfaces/classes... => Here can move App classes to other frameworks /Technologies for execution becoz they are developed as ordinary /simple java clases... eg:: hibernate (all versions) , spring all versions , Struts 2.x and etc... type :: java ORM framework/Tool or Implementation s/w of JPA Specification Vendor :: SoftTree / RedHat / JbossVendor (Adivision of RedHat) 6.x (under development) (compitable with java8 or 11) 5.x-> 5.4.18 (stable version) (compitable with java 8 or 11) (|-->Developed based on jpa2.2 to specification) creator =: Mr. Gavin king Open Source JPA :: JAva PErsistnece API. version :: JVM based languages are scala, groovy ,kotlin ,java and etc... To download s/w :: download as zip file from www.hibernate.org website... https://sourceforge.net/projects/hibernate/files/hibernate-orm/S.4.18.Final/hibernate- release-5.4.18.Final.zip/download reference Books :: Persistnece with Hibernate by Gavinking -->Hidernate supplied ref docs +api docs + class room content... To install s/w :: Extact zip file (hibernate-release-5.4.18.Final.zip) =>use \changelog.txt file to know which version is released in which year. => \documentation folder gives api docs and ref doc: =>\lib folder gives libraries (Jars ) =>\project folder gives > titility files “lasses — -> source code -> sample Apps, projects and ete... Defination: ,non-invasive Hibernate is an open source , light weight , Portable and integrated java based ORM framework or Tool that is given based on JPA Sepcification rules and guidelines to develope objects based o-r mapping persistence logics. ‘open source along with hibernate installation we get its source code.. and more over hibernate frramework free s/w .. This hibernate as_an Open source framework. makes Light weigtht Hibernate is ligtht weight becoz (a) Hibernate f/w Is given as zip file having less size (In mbs) (b) To develope and execute Hibernate Persistence logic we just need JDK/JVM and hibernate libraries(jars) , i.e there is no need of arranging the heavy weight servers / containers (c) By creating object for "org.hibernate.cfg.Configuration" class we can activate Portable /bootstrap hibernate any where.. => Using hibernate we can develop persistence logic as objects based persistence logic with out using any SQL Queries support. This makes hibernate persistence logics DB s/w indepedent persistece logics and also portable across the multiple DB s/ws... note:: This feature helps to change the DB s/w in the middle of the development and also in the middle of the production. Integratable SAY =>we can place hibernate peristence logic in different types of java applications to make them interacting with Db s/w like we can place hibernate persistence logic in standalone JAva app, in web applications, in distributed Apps and etc.. This makes hibernate persistence logic as easily integratable logic with diff java technologies and frameworks and also in different types of Apps... High level architecture of Hibernate To Common features of hibernate that implemented based JPA Specification use JPA based programming. To use direct features of hibernate which are not there in JPA specification then use Retetional Datanase Hibernate Native API... Why the Hibernate is named as Hibernate? Itis given based on hibernation word.. The Hibernate Programming represents DB table record through objects and keeps them cache .. looks like hibernation. So this framework Is called as hibernate. Hibernate Configurations (‘ instructions/information to underlying container /Server /Framework/JVM) 1. xml driven Configurations (old -—> used only in maintenance projects) 2. annotation driven configurations (Latest --> used in all projects) https://www.youtube.com/watch? [ Compoments in Hibernate Programming while working with Xml driven cfgs ] v=io2TciOcF2Y&list=PLVIQHNRLfIP9OITKTQuq3U WINA_wOPIFr&index=39 DAO class ( class having Persistence AN Togic) (2h AV /Activate Hibernate F/w —_—~ --->For Java Bean a https://www.youtube.com/watch? hibernate configuratibn file \ v=Bw3v1b3WjDM&list=-PLVIQHNRLFIPBunkTii_FNKDfow3HS (xml fild) C6RL&index=5|6|7 apis ) Entity Class/ . 0-t mapping persietenbaleasey: ~-> for language, Technology , framework knowledge. «= persistence logic | Model Class/ hibernate mapping fle = (xml fild) This DAO can be there in java based serviet/jsp web app, struts App) -~ Spring App, spring Boot App, webService comp , spring MVC App Standalone App and etc.. DAO class (Data Access Object Class) ‘The java class that seperates persistence logics from other logics of the application and makes them reusable and flexible to modify is called DAO class... wart diagram (a) DAO class uses hibernate api and activates hibernate framework (b) The activated hiberate f/w interally uses the given hiberante configurations as inputs like hb configuration file, mapping file , entity class and etc... (c) DAO class again uses hibernate api to develop objs based o-r mapping persistnce logic (d) The _0-r mapping makes Hibernate f/w to generaed JDBC code with SQL query to perform Persistence operation on DB s/w (e) the genrated SQL query executes in Dbs/w and manipulates the data of the DB s/w (f) Generated results come back to DAO class hibernate configuration file > any .xml can be taken taken hibernate cfg file... => if no file name is specified, then the hibernate f/w takes hibernate.cfg.xml of classpath /build path as default hibernate configuration file.. =>This file contains info about , how the hibernate f/w should locate and establish the connection with Db s/w i.e we specify jdbc driver details.. (mandatory) (idbcdriver classname, jdbc url , db username, paswword) => we can also speficy Dialect comp details (optional) using which Hibernate generates SQL queries internally... (Based on jdbc driver details we specify HB f/w can pick up the Dialect comp details dynamically..so it is optional to specify) => This file to use to given common instructions to hibernate f/w like enabling autoCommit, enabling caches , enabling SQL query show and etc.. (optional) => Hibernate cfg file generally contains a) jdbc properties (jdbc driver details) (mandatory) b) hibernate properties (like dalect info, showing sl, formatting sa, auto generation DDL and etc.) c) Hibernate Mapping file names.. pee (mandatory) => we given same Info by using hibernate.proeprties file... but that as become legacy..(old) => This Hibernate configuration file information can be given as key value pairs where keys are fixed and values will be chanaged based on DB s/w, jdbc driver and hibernate s/w names and versions we are using... eg: tt Oracle hibernate.dialect_ _org.hibernate.dialect.Oracle8iDialect’ | we use one of these hibernate.dialect _org.hibernate.dialect.Oracle9iDialect but optional hibernate.dialect _org.hibernate.dialect.Oracle10gDialect hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver hibernate.connectior ername ora jdbc properties hibernate.connection.password ora (reanderary) hibernate.connection.url jdbc:oracle:thin:@localhost:1521:orcl (collection from \project\etc\hibernate.propertjes file) =>We develop this configuration file on 1 per DB s/w basis.. If our App is talking with 1 Db s/w .. then we take 1 hibernate cfg file... otherwise we take multiple configuration file... note:: dialect comp is internal part of hiberante f/w having capability to Generate SQL Queries internally based on the DB s/ws we use.. In hibernate.cfg.xml (Partial Code) "hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver bernate.connection.url">jdbe:oracle:thin:@localhost:1521:xe bernate.connection.username">system ‘connection. password" >manager hibernate mapping file name Entity Class /Model class/Persistence Class/Domain class ‘able Data (to be inserted to DB) or It is java bean class whose objects holds pet Persistent data (colleted from DB ) It will be taken on 1 per Db table basis => while writing objects based o-r mapping persistence logic .. we use this objects to represent DB table records and to perform Persistence operations => These are non-invasive classes .. that means these classes need not implement or extend from hibernate api interfaces/classes. => We can design these classes using all java oop features like inheritence composition polymorphism and etc.. DB table in Oracle /fEntity class public class Employee implements Serializable{ eae’ Recomanded.. (optional) private int eid; |—>esalary (n) private String ename; |—->eaddrs (ve2) private float esalary; private String eaddrs; I [setters && getters public void setEid{int eid){ this.eid=eid; public int getEid{){ return eid; } mapping note:: when we are Entity classes with DB tables ,there must be compitability b/w Entity classes properties count and type with Db tables cols type and count. hibernate mapping file => any .xml can be taken as hibernate mapping file... but every file mapping name must be specified in hibernate cfg file using tag. => This file contains diff o-r mapping cfgs ... like mapping Entity classes with DBtables and mapping properties of Entity classes with the colums of Db tables.. Recomanded notation of this file name is .hbm.xml There is no default file name for hibernate mapping file..So Every file name must be specified in confiuration file.. => we generally take these mapping files on 1 per Db table basis. In Employee.hbm.xml (sample mapping file) _(partial-Code) for other columns related | properties cfg... Entity classes --> 1 per Db table basis HB Mappingfiles-—-> 1 per Db table basis HB Cfgfiles —> 1 per Db s/w basis Naming Conventions Oracle DB coupe HB configuration file name :: hibernate.cfg.xml Keine j Entity classes names :: Employee ,Student bhitables mapping file names :: Employee.hbm.xml Student Student.hbm.xml Employee emp=new Employee(); emp.setEld(1001); emp.setEname("Raj emp.setEaddrs("hyd’ emp.setEsalary(9000); (Se3jsave(emp gives save object persistence instruction to Hiberate f/w. (insertint record) hibernate session obj is no way related Servlet Session object... hibernate Session object is con++ (i.e con object + xml files info) Features of Hibernate framework => Allows to devleop Objects based DB s/w indenpendent o-r mapping persistence logic with out any SQL Queries. => Avoid jdbc boilerPlate code... => Supports both Xml driven , Annotation driven cfgs.. => Hibernate Light weight framework. we can bootstrap/activate HB by just creating object for "Configuration class". => The entity classes of hibernate are non-invasive i.e they can moved and used in other frameworks => All exeptions in Hibernate are unchecked exceptions. So no need of catching and handling method... more over.. they automatically exception Propagration.. => Supports both Local and Global Transactions.. and we can change from Local to Global and vice-versa .. with out toughing hibernate persistnce logic.. by just modifying xml file. =>Supports Versinoning and timestamping, => allows use all java features while developing entity classes... polymorphism , association and etc... ‘Auto Schema Generation (DB table creation) supports both single row and bu Ik row operations |-PHOL/JPQL —HQL—>Hibernate Query Language DB s/w | JPQL —-> Java Persistence Query Language | independent ike inheritence ,composition, |—>NativesQL (Original SQL queries) |-->Criteria API /QBC (Query By Criteria) =>Allows to call PL/SQL procedures and functions... (from hibernate 3.x) =>Supports Lazy Loading .. (Delays the hittin process of DB s/w) =>Gives generators(12+) to generate PK col values /Identity values dynamically => Gives callback interfaces to write plain jdbc code.. by getting jdbc objs... and etc... How does ORM framework /hiberante performs synchronization b/w Objects and DB table rows? //Entity class public class Employee{ EMPLOYE! private int eno; roperty private String ename; eno ee Leno private String eadd; propertie: private float salary; of //setters & gettrs Entity class ) salary(float) 9000 10060 “ 15000 ORM framework (Hibernate) uses Each object id value as the criteria value to perform sync b/w Object and Db table row.. i.e it uses id value as criteria value while generating select ,update queries of synchroization. But choosing and configuring one property of Entity class as id property/identity field in the mapping file is the resposibility of the Programmer... JVM identifies the object using its hashCode.. where HB indentities the Entity class object using its id value (Id field/id property value). similarly DB table identi rownum or using pk col value.. the record either using How we need to analyze while configuration propertie(s) as Id Propertie(s)/Id Field(s) in Hibernate Mapping file’ from Entity class? => if PK constraint is applied on one column of the DB table then it is called singularPK PK constraint is applied on multiple columns togather belonging to the DB table then itis called Composite PK if we cfg single property of entity class as id field/property then itis called gular id field /property. if we cfg multiple properties of entity class togather as id field/property then it is called composite id field /property. if Db table is having singular pk... then take that pk colum related property of Entity class and configure it as singular ID field using in mapping file if Db table is having composite PK then take that pk column related multiple properties of Entity class and configure them as composited ID field/property using of mapping file... if Db table is given with out PK colums , unique key cols then better to reject those db tables to use in Hibernate. Is It mandatory to have PK column in DB table while using that db table in our HibernateApp? Ans) No, but itis recomanded to place... to avoid synchroization issuses... sample Employee.hbm.xml Singular Id Field cfg.. portant Objects of Hibernate PErsistence logi Keeping these 3 objects ready is called Boostraping of hibernate (Activating hibernate) (a) Configuration object (b) SessionFactory object (c) Session object Configuration obj => By creating object for this concrete class .. we activate Hibernate f/w by collecting Hibernate jars /libraries from the classpath or build path. we should add => Takes hiberante configuration file name and location as hibernate botne>\\ii\tequirad folder jars input value and also take hibernate mapping names and locations through hibernate configuration file name. => This class is given based on builder Design Pattern... =>Using this object we can create HB SessionFactory object... => if no hibernate cfg file name is supplied .. then it will take hibernate.cfg.xml file from classpath (src folder of ecplise project) as default hibernate cfg file name.. GAstivate Hibernate 1/28 vfiguration(); //Supply HB cfg , mapping file names.. cfg.configure(); —>Takes hibernate.cfg.xml of classpath as cfg file name cfg.configure("com/nt/cfgs/mycfg.xml"); ~>Takes given mycfg.xml as hibernate cfg file name SessionFactory object => Designed based on Factory Desing Pattern providing abstraction towards Session object creation. => The configuration object internally reads the entries of configuration file, mapping files and creates different services like jdbc con pooling, caches, dialect , Transaction Manager, o-r mapping metadata, and etc... and uses them in the creation of SessionFactory object step by step by defining given based on buidler desing pattern.._o-r process. So we say Configurati Itis heavy weight object becoz it cotains multiple small objects reprsenting different comps and services. => It is Long lived in the application.. Itis immutable object (i.e once data is set to this object we can not modify that data ) => Immutable objects Thread Safe objects ,So the SessionFactoy object is also thread safe. SessionFactory facto ionFactory object, first by creating multiple objects SessionFactory object creration..(builder DP) si and uses them =>SessionFactory object means it is the object of java class that implements org.hibernate.SessioFactory(I) => SessionFactory , Configuration objects we generally on 1 per DB s/w basis in our Apps. Session object is con++ object i.e it contains jdbc con object that is collected jdbc con pool represented by SessionFactory object and lots o-r mapping MetaData Info (++ means o-r maping metadata info) => Created through SessionFactory object => It is base object for programmer to give persistnece instructions to Hibernate F/w using class objects. => It is mutable object , So it is not thread safe by default. => It is short lived object in App ... using SessionFactory object we create session objects =>We geneally take Session object either 1 per each Persistence operation or 1 per related Persistence operaitons... => Itis light weight object... => It comes with one built-in Level1 cache.. having capability to hold Entity class objects.. =>SEssion object means .. It is the object of the class that implements org.hibernate.Session(I) ‘Onfiguration Ly oerante-cig. xm] ob} files =>Since configuration object is creating the Complex SessionFactory object by using multiple small objects like dailect, con pool and etc.. step by step by defining certain prcoess. So we can say "Configuration" is given based Buidler Desing pattern.. In java local variables , synchorinized objects and immutable objects are thread safe.. Featory PAttern says to client. u ask object,, i will object .. but u do not worry about how i am creating object... Factory Pattern provides abstraction on object creation process... ig files orm framework (like hibernate) Gives Persistence instructions uing Hiberante Persistence operations Bulk operations Single row operations SHE, POL HAQL:: Hibernate Query language Hest mlee ->Native SQL JPQL :: Java Persistence Query Language a tecoed italia) ->Criteria API/QBC QBC :: Query By Criteria ses.save(-) | for saving object ses.persist(-) | (insert) ses.load(--) | for loading object ses.get(-,-) {select ) ses.update(-) | for updating the object ses.delete(-) | for deleting object ses.saveOrUpdate(-,-) | for saving /upating object ses.merge(-,-) | for merging object ses.refresh(-) | For reloading the object and etc... note:: In hiberate or o-r mapping programming > saving object means writing object's data to db table as record > loading object means selecting record from Db table to Entity class object > updating object means updating the record represented by the object > deleting object means deleting the record represented by the object Procedure to develop First Hibernate App performing save object operation step1) keep the s/w setup ready ->Hibernate latest version :: (5.4.18) Be ->Jdk (1.84) myeclipse -> Oracle (11g +) netbeans ->Eclipse (2019-12) (Extract zip file / use installer) ached : - i JCreator eclipse-jee-2019-12-R-win32-x86_64. Inevlanes ->SQL Developer (for oracle) anulisien (GUI Db tool) . . . popular one is :: Eclipse with STS plugin step2) create DB table "Product" in oracle Db s/w using SQL Developer tool Product |—>pid (n) (singular pk) |—>pname (vc2) |—>price (float) |—>aty (float) CREATE TABLE "SYSTEM"." PRODUCT" ( "PID" NUMBER(5,0) NOT NULL ENABLE, "PNAME" VARCHAR2(20 BYTE), "PRICE" FLOAT(126), "QTY" FLOAT(126), CONSTRAINT "PRODUCT_PK" PRIMARY KEY ("PID")) step3) Launche eclipse IDE by workspace space folder.. The folder where projects will be saved... step4) create Java Project in Eclipse IDE.. File > new > project > java project > name:: HBProji-SaveObject > finish.. step5) Add Libraries(jars) to the build path /classpath of the Project.. all ar files collected from \lib\required folder ojdbc6/7/8.jar Right click on project > buildpath > configure build path >Libraries tab > add external jars > browser and select jar files.. note:: if App is using third party apis then those apis related both main and dependent jar files must be added to CLASSPATH/Buid path.. step6) Create packages in the Project and develop the source code bject] |-—>Product,java (Entity class) Product.hbm.xml (Hb mapping file) om.nt.cfgs |—>hibernate.cfg.xml_ (HB cfg file) |—4com-nt-test | >SaveObjectTest.java (Client App having Hibernate based o-r mapping persistence logic) ctrl++/— —> for increasing or decreasing instant font. .. through the serialization of Entity class objects i,e writes Entity class objects data to files of Harddisk using the concept of Serialization. but Serialization is possible only on Serializable objects.. To make objects as Serializable we should make the class of the objects implementing java.io.Serilizable(|) (Marker Interface-Empty interface) Hiberante supports disk cachin note:: All Entity classes should be developed as java bean classes .. implementing java.io.Serializable(I)... Programmer/Hibernate uses setter methods to set/modify data of Bean objects and getter methods to read data from bean objects. ctrltshift+L :: To get all short cut keys... step7) Run the the Application Go to client App ctrl+F11 (or) Right click on Client app source code —> run as ~>java App. Hiberante is giving DTD/XSD rules for both hb cfg file, hb mapping file to make all developers working with same tags, attributes in the development hibernate cfg file , hibernate mappig files... DTD :: Document type definitation XSD :: Xml schema definitation (latest) These are Building block of xmi files.. Collect DTD/XSD rules import statements for creating HB cfg file or HB mapping file from sample cfg files , mapping files of \project\ folder.. | cfg file Can we develop single xml file having both hb cfg and hb mapping info? Ans) No.. Becoz Hibernate f/w is expecting DB connectivity details from HB cfg file and_o-r mapping details of diff calsses and db tables from Hb mapping files whose file names are specified through HB cfg file.. So we can not mixup both.. sample note:: we can collect mapping fiels and same hibernate cfg from \project folder... note:: we can get the fixed property names of hibernate cfg file from \project\etc\hibernate.properties.. =>All non-select operations in hibernate must be executed as transactional statements.. So that we can commit or rollback thoese operations.. true makes ernate f/w to show the generated SQL query as log msg Hibernate: insert into PRODUCT (PNAME, PRICE, QTY, PID) values (2, ?, ?, ?) The word "hibernate" is optional in hibernate cfg file properties. SessionFactory object meas it is the object of java class that implements org.hibernate.SessionFactory(-). Since this class name chanages hibernate version to. version ..we always refer by using the common "SessionFactory(|)" ref variable... System.out.printin("sessionFactory object class name::"+factory.getClass()); sessionFactory object class name::class org.hibernate.internal.SessionFactorylmpl Session ses=factory.openSession(); | con++ the factory.openSession() method is given based on Session obj factory desing pattern performing following operation —_djlecton. =>collects con object throguh Datasource object of (C_)Cobp) Devel cache SessionFactory from its jdbc con pool , also collects \iapping file J mapping file metaData and dialect.. to create and nietedebe?” SEssion object having all these objects.. SEssionFactory holds huge no.of object representing huge no.of services. where as session holds less objects representing lesss services. SEssion object it is the object of java class that implements org.hibernate.Session(I) and this class name chanages version to version of hibernate. So we refer Session object with org.hibernate.SEssion(|) variable (common variable) System.out.printin("'session object class name::"+ses.getClass()); session object class namez:class org.hibernate.internal.SessionImpl org-hibernate.Session(I) Sears ge obnenaD extends o “ a . extends org.hibernate.engine.spi.SessioniImplementor(I) implements org.hibernate.engine.spi.SessionFactoryimplementator(I) org.hibernate.internal.SessionImpl (c) ‘caplennients org.hibernate.internalSessionFactorylmpl\(c) note:: Web applications's HttSession object is no way related to HB session object...

You might also like