/
2009 coreservlets com 358548 2009 coreservlets com 358548

2009 coreservlets com 358548 - PDF document

trish-goza
trish-goza . @trish-goza
Follow
363 views
Uploaded On 2016-06-11

2009 coreservlets com 358548 - PPT Presentation

HibtQi Hib erna e Originals of Slides and Source Code for Examples Customized Java EE Training httpcoursescoreservletscomServlets JSP Struts JSFMyFacesFacelets Aj ID: 358548

HibtQi Hib erna e Originals Slides and

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "2009 coreservlets com 358548" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

© 2009 coreservlets.com HibtQi Hib erna e Originals of Slides and Source Code for Examples: Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Aj © 2009 coreservlets.com For live Spring & Hibernate training, see thtt//lt/ courses a t t Taught by the experts that brought you this tutorial. Availableatpublicvenuesorcustomizedversions Available at venues can be held on-site at your organization. CdlddthtbMtHll an d t ht b y M H a Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topicsCourses developed and taught by coreservlets.com experts (edited by Marty)Spring, Hibernate/JPA, EJB3, Ruby/RailsContact hall@coreservlets.com for details To ics in This Section p •Briefl y review SQL q uer in yqyg Discover Hibernate’s different approachestoqueryinga approaches a Getacquaintedwiththe‘Queryby Criteria’ technique •Introduce the ‘Query by Example’ offshoot © 2009 coreservlets.com Qi Q uery Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at Quer for Data yg •Pull back specific data from a database Retrieve a specific object Retrieve a collection of a specific object typeRetrieve a collection of different object types •In the database, handled through the Structured Query Language (SQL) SELECT statements for querying Quer Terminolo gy yggy •Restriction down the results ( rows based on s p ecified criteria g()p In SQL, accomplished with the use of conditions appearing in a FROMEBILL WHEREEBILLID=1 ; EBILL EBILL _ SELECT * FROM EBILL �BALANCE 1000 Nidthdt(l)t g d t co we re t In SQL, accomplished by identifying columns in the ‘select’ clause _ �FROM EBILL WHERE AMOUNT 1000 ; _ ; SELECT EBILL_ID, EBILLER_ID, BALANCE, DUE_DATEFROM EBILL WHERE EBILL_ID=1;• Groupingsimilarresultstogetherbasedoncommonattributes similar SELECT EBILLER_ID, AVG(BALANCE)FROM EBILL GROUP BY EBILLER_ID; Quer for data yg SQL statements can be simple… SELECT*FROMACCOUNT – * Returns all the records from the account table Returntherowofdatafortherecordwithaccountid1 account 1 …or more involvedSELECT AO ABALANCE ., ACCOUNT_OWNER AO, ACCOUNT A WHERE �A.BALANCE 500 AND AACCOUNTIDAAOACCOUNTIDAND _ AAO _ Returns a list of all the account owners who have accounts with a balance over $500 SQL Quer y O �// projection [ WHERE ] // restriction [ ORDER_BY ] // ordering [ GROUP BY ]// aggregation [ HAVING ]// group restriction diti() ) � Quer with Hibernate yg Provides multiple interfaces for querying QuerybyID – Query by Criteria–Query by Example Hibernate Query Language • Relievesthedeveloperofhavingtoknow • Relieves Hibernate understands the underlying database and knows how to write more • Flexible • Flexible data, it provides hooks for you to write your own © 2009 coreservlets.com QbID Q uery y Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at Quer Retrieve an object by its ID •Most common and easiest a roach to obtainin g ob j ects ppgj Fastest type of query, but can only return a sin g le ob j ect at a time gj –Assuming primary key index on the id column Account account = (Account)sessionget( (Account)session . © 2009 coreservlets.com QbCiti Q uery y a Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at Quer Criteria ( QBC ) yy() Build a query by defining multiple ‘Criterion’ – Specifyconstraintswithoutdirectstringmanipulations Specify May result in less readable code than other methodsRealized through four Hibernate interfaces Base object for QBC, created off the Session, Contains all the restriction/projection/aggregation/order – org.hibernate.DetachedCriteria org.hibernate.DetachedCriteria Same as Criteria, but created without the presence a Later, attached (like detached objects) to a session and executed executed Think of each Criterion as a ‘where’ clause addition Utility class used to create Criterion objects org.hibernate.Criteria Create by passing the session a ‘root’ class –session.createCriteria(String className); • Addrestrictions • Add addCriterion(Criterion criterion);•Think ‘where’ clause Join to an association, assigning the li(iiihili) – createA ng assoc i at , Str i ng a Still thinking ‘where’ clause Addorder Think ‘order by’ org.hibernate.Criteria Get results of the q uer as a List of qy root objects – list Get result of the query as a single root ob ect No session required to create –Created by calling static method, providing a ‘root’ class• DetachedCriteriaforClass(StringclassName); Contains most of the methods from the Criteriaclass Criteria list(), uniqueResult() etc… To execute, create regular Criteria instance off of detached version EblCii(Si) – C r i ) ; org.hibernate.criterion.Restrictions lt(String propertyName, String value); • gt(StringpropertyNameStringvalue); • gt(String eq(String properyName, String value); p Strin g value ); (gppy,g); like(String propertyName, String value);isEmpty(String propertyName, String value); isNotEmpty(String propertyName, String value);isNull(String propertyName, String value); • isNotNull(StringpropertyNameStringvalue); • isNotNull(String in(String propertyName, Collection values); Ma p q(pppy); between(String propertyName, Object lo, Object hi); Hibernate Criterion Interfaces •org.hibernate.criterion.Property Way to represent query restrictions orghibernatecriterionOrder • . . Order Data container used to represent an ordering scheme– SingleCriteriaobjectcancontainmultipleorders contain Created through static method, passing in attribute to sort Hibernate utility class to help identify returned columns CtdthhttithdiththPjti – d c me th o d s on e ith er e ro ec of Property classes Query Building Retrieve List of Ob j ects // retrieves list of all Savings Account ObjectsCriteria criteria = session.createCriteria(SavingsAccount.class);List savingAccounts = criteria.list(); RootEntity:SavingsAccount // order savings accounts by balance, ascendingCriteria criteria = sessioncreateCriteria(SavingsAccountclass) Root . List savingAccounts = criteria.list();Attribute Name // polymorphic query –Criteria criteria = itCiti(Atl) sess on.crea C r .c ass Root Entity: Account Retrieve Sin g le Ob j ect // retrieve an AccountOwner...Criteria criteria = session.createCriteria(AccountOwner.class);// ...with a specific email address CriterionrestrictByEmail = // add restrictByEmail to criteria criteriaadd(restrictByEmail); Attribute Name, Value criteria . // ...and we know there can be only oneAccountOwner marty = (AtO)itiiRlt() (A ccoun tO wner cr it er a.un que esu lt() // same commands -shortened to one line of code AccountOwner marty = (AccountOwner)session.createCriteria(AccountOwner.class) ueResult() Creating Criterion: RestrictionsandProperty Restrictions // shortened version from previous slide, // using Restrictions AccountOwner marty = (AccountOwner)session.createCriteria(AccountOwner.class) " , " " ) Restrictions.eq(email,hall@coreservlets) ________________________________________________// could also have written using the Property class AtOt(AtO)i A ccoun tO wner mar t y = (A ccoun tO wner sess on.createCriteria(AccountOwner.class)Property.forName("email").eq("hall@coreservlets.com") Usin Dot Notation on Ob j ects // can use dot notation to access component attributes Listaccounts=session List = .add(Restrictions.eq("address.zipCode","21045") // also valid with Property objectLi st n sess o n staccoutssesso Property.forName("address.zipCode").eq("21045") (); (); 'Between' and 'In' Clauses // using ‘ Listaccounts= = Restrictions.between("balance",100, 500) o n n t I 1L 2L 3 L og[]accoutds{,,3}; List accounts = session.createCriteria(Account.class) ert .forName "accountId" .in accountIds py()() Strin Matchin g ( like clause ) gg() // String matching ListaccountOwners = Restrictions.like("lastName","H%").ignoreCase() ________________________________________________ // Alternate String matching.// MatchMode.END and MatchMode.EXACT also availableList accountOwners = session.createCriteria(AccountOwner.class)Property.forName("lastName").like("H", MatchMode.START).ignoreCase() lit() . s ; g Multi p le Criterion gp // adding multiple criteria results in an ‘ ListaccountOwners= = Restrictions.ilike("lastName","H%") " , " " ) Restrictions.ilike(firstName,M%) Can also use 'ilike‘ for case insensitive ________________________________________________ wi h Pr ope t i a l //ostopetesaso List accountOwners = session.createCriteria(AccountOwner.class) ert .forName "lastName" .like "H%" py()() Property.forName("firstName").like("M%") Or’ing Multiple Criterion usingOr/And using Or/And //option1 useRestrictionsorandRestrictionsand // 1 – . . // retrieve accounts where: //1)lastnamestartswith ‘ H ’ andfirstnamewith ‘ M ’ H M // OR// 2) email address ends in ‘ ListaccountOwners Restrictions.or( ct o n n estctos.ad( ) Or’ing Multiple Criterion usingDisjunction/Conjuction using // option 2 – u // Restrictions.disjunction// retrieve accounts where: //1)lastnamestartswith ‘ H ’ andfirstnamewith ‘ M ’ H M // OR// 2) email address ends in ‘List accountOwners = sessioncreateCriteria(AccountOwnerclass) session . . Restrictions.disjunction().add(Restrictions.conjunction() dd(Rtitilik("ltN""H%")) .a dd(R es i c lik tN ame Restrictions.like("email","%coreservlets.com") Adding Your Own SQL – UsingDatabaseFunctions Using // use the sql ‘ //withlastnamesgreaterthen10characters // List accountOwners = session.createCriteria(AccountOwner.class).add( Hibernate.INTEGER Hibernate.INTEGER Need to put an ‘alias’ place holder for the table name, which will come from the root entitiy, AccountOwner Adding Your Own SQL – JoiningTables Joining // retrieve accounts where all the transactions made //bytheaccounthavebeenlessthan$500 // List accounts = session.createCriteria(Account.class).add( whereatx.accountid = {alias}.accountid) " where _ ) Again, ‘alias’ place holder for the table namewhichwillcomefromtheroot Oracle and Derby evaluate ‘all’ to ‘true’ iftdithblt name , entitiy, Account if no rows are re t urne i e su b se Creating Detached Criteria Queries DetachedCriteria detachedCriteria = DetachedCriteria.forClass(AccountOwner.class) DetachedCriteria.forClass(AccountOwner.class) .add(Restrictions.ilike("lastName","H%"));Session session = HibernateUtilgetSessionFactory() HibernateUtil . Criteria regularCriteria = detachedCriteria.getExecutableCriteria(session);List accountOwners = regularCriteria.list(); _______________________________________________________// can also be combined into one lineList accountOwners = detachedCriteria.getExecutableCriteria(session) Data with Joins g ebIllers is the name of the association that appears In the root entity’s mapping file session.createCriteria(EBill.class);// build the EBiller criteria off the EBill criteria CriteriaebillerCriteria = ebillerCriteria.add(Restrictions.like("name","VISA")); // return all the EBills issued from VISAList ebills = ebillCriteria.list(); ______________________________________// can be combined into a single like of codeCriteria ebillCriteria = session.createCriteria(EBill.class) session.createCriteria(EBill.class) .createCriteria("ebiller" Restricting Data with Joins – UsinganAlias Using Alternate approach using an alias and only creatingoneCriteriaobject creating // single line approach from previous// slide using two Criteria objects CriteriaebillCriteria= Criteria = createCriteria(EBill.class)("ebiller").add(Restrictions.like("name", "VISA")); ebIllers is the name of the association that ears In the root entit y ’s ma pp in file // use an alias , and create a sin le Criteria ob ect ppyppg //,gj Criteria ebillCrit = session.createCriteria(EBill.class)("ebillers", "eb").add(Restrictions.like("eb.name", "VISA")); Criteria Ob j ect Joinin g jg Currently, only joining of associations td are suppor t e d &#xmany;&#x-to-;&#xmany; Cjiii i n i s no at this time – Receive failure that the property you want to reference does not represent an entity association Thiftlikltbdddithft – Thi s l y t o b e a dd e d i n e near f u t Forcin Ea g er Loadin g ggg Indicate in the Criteria to fully load all bjd i o ects, an d to use prox i esIf already setup to fully load in the object mapping file (ienolazy =" etc)thisisunnecessary . e lazyfalse … ) also unnecessary. Hibernate will automatically load bjfdiii o ects re f erence i n restr i ct Listebillers List ebillers .setFetchMode("ebills", FetchMode.JOIN) .list(); Indicates that the “ebills” collection should be fully loaded for each EBiller instance Result Transformers – DefaultBehavior Default Transformers map the returned result sets Jbj to ava o bj ectsBy default, maps returned result sets to the Root Entity object object // this…List accounts = session.createCriteria(Account.class) Default results transformer maps the result set into the Root Entity indicated in the // …is the same as thisList accounts = session.createCriteria(Account.class) Result Transformers – DistinctEntityResults Distinct • Eliminates any duplicate objects // transformer eliminates any duplicate objectsList accounts = session.createCriteria(Account.class) Result Transformers – ReturnMultipleObjectTypes Return • Returnsalistofmapswhereeachmaphasaninstanceof a all the objects identified in the query (on a per-row basis) ListmapList = for (Object aResult : result) {Map map = (Map) aResult; Att accoun = (Account)map.get(Criteria.ROOT_ALIAS);AccountTransaction atx = (AccountTransaction) map.get("atx"); Hibernate Pro j ections j •Restricting returned columns Only bring back objects/columns you want to see Created off of either the Projections of Property Property.forName () Cltt d • an map resu lt s o a non-manage d Java class Hibernate Pro j ections j // retrieve id, balance and creation date //dtth ddt // an d se t th em on a non-manage d summary dt List summaryList = .as("accountId")) add( Projectionsproperty( " " ) add( property(creationDate) new AliasToBeanResultTransformer(AccountSummaryDTO.class) Hibernate Pro j ections j // can also be coded using Property class //insteadofProjectionsclass // instead of Projections class List summaryList = . .add(.as("accountId")) add( PropertyforName("balance") . add( new AliasToBeanResultTransformer( Sl) Account S and Grou p in gpg // Returns a collection of Objects[] with 4 fields// 1) Account id // 2) A single EBiller id on that account session.createCriteria(Account.class) session.createCriteria(Account.class) .createAlias("ebills", "e").add(Property.forName("accountId") .group() t() .avg())); No ‘Having’ feature available at this time – Planned for a future release © 2009 coreservlets.com QbEl Q uery y Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at Exam p le ) yyp() •Set u p exam p le ob j ect ) for ppj() Hibernate to use to generate a databasequery database query Create ‘Example’ criterion based on these objects objects • p Create by using static create(Object obj); – Creates an Exam p le ob j ect used for q uer for pjqyg the supplied object type Quer Exam p le yyp // setup an owner with last name 'Hall' AtOAtO() A ccoun tO wner owner = new A ccoun tO // create an ‘example’ criterion based on user Examplecreate(owner); Example . // use the criterion to execute the // query for owners named 'Hall'List hallList = sessioncreateCriteria(AccountOwnerclass) session . . .add(.list(); Exam p le Ob j ect gppj Certain fields ignored by default ObjectIdentifiers – Object Identifiers –Version property– Anynullvaluedproperties Can also specify: enableLike(MatchModemode); – enableLike(MatchMode mode); Enable ‘like’ matching for all String attributes g nore case for all Strin g attributes gg –Excludes zero-valued properties–excludeProperty(String name); Eldtildt • d e a par ti cu ar name d proper t Do not exclude null or zero-valued properties Combine Example and TraditionalCriterion Traditional = Example.create(owner); // execute the query for owners named 'Hall'// who also live in the state of Maryland List hallList = session.createCriteria(Acc add( ) .add(dress.state", "MD")).list(); Combine Multiple ExampleCriterion Example // account owners named Hall AccountOwnerowner=newAccountOwner(); AccountOwner = Example exampleOwner = Example.create(owner); // accounts with a balance of 1000Account account = new Account(); account.setBalance(1000); account.setBalance(1000); Example exampleAccount = Example.create(account); // r y r wn s ll' wi h ba a n o 000 //queyooesaedatbaaceso000 List hallList = session.createCriteria(AccountOwner.class) leOwner exampleAccount Great Place for QBE Applications with GUI pages that allow ltilttibt mu l e a tt r u t as search criteria Example: © 2009 coreservlets.com W W rap-up Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at Summar In this lecture, we: Reviewed traditional SQL querying and established terms – IdentifiedseveralapproachesprovidedbyHibernateto – Identified several query a databaseWalked through Query by Criteria (QBC) and Query by l()ihddldbh Examp query i ng met h o d s, an d l earne d out t h e core Hibernate classes involved in querying• • Preview of Next Sections •Hibernate Quer y Lan g ua ygg Calling native SQL through Hibernate Hibernate 53 © 2009 coreservlets.com Qti? Q ues ti ons Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at