14 hql

690 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
690
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
35
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

14 hql

  1. 1. Professional Open Source™ HQL© JBoss, Inc. 2003, 2004. 07/17/04 1
  2. 2. Steps involved in querying Professional Open Source™  A query must be prepared in application code before execution. So, querying involves several distinct steps: – Create the query, with any arbitrary restriction or projection of data that you want to retrieve. – Bind runtime arguments to query parameters; the query can be reused with changing settings. – Execute the prepared query against the database and retrieval of data. You can control how the query is executed and how data should be retrieved into memory© JBoss, Inc. 2003, 2004. 2
  3. 3. Creating a query object Professional Open Source™  To create a new Hibernate Query instance, call either createQuery() or createSQLQuery() on a Session. The createQuery() method prepares an HQL query:  Query hqlQuery = session.createQuery("from User");  To obtain a Criteria instance, call createCriteria(), passing the class of the objects you want the query to return. This is also called the root entity of the criteria query, the User in this example:  Criteria crit = session.createCriteria(User.class);© JBoss, Inc. 2003, 2004. 3
  4. 4. Paging the result Professional Open Source™  Query query = session.createQuery("from User u order by u.name asc");  query.setMaxResults(10);  In this Criteria query, the requested page starts in the middle of the resultset:  Criteria crit = session.createCriteria(User.class);  crit.addOrder( Order.asc("name") );  crit.setFirstResult(40);  crit.setMaxResults(20);© JBoss, Inc. 2003, 2004. 4
  5. 5. Using Named Parameters Professional Open Source™  String queryString = "from Item item where item.description like :search";  The colon followed by a parameter name indicates a named parameter. Then, bind a value to the search parameter:  Query q = session.createQuery(queryString)  .setString("search", searchString);  Often, you’ll need multiple parameters:  String queryString = "from Item item“ + " where item.description like :search"  + " and item.date > :minDate";  Query q = session.createQuery(queryString)  .setString("search", searchString)  .setDate("minDate", mDate);© JBoss, Inc. 2003, 2004. 5
  6. 6. Using Named Parameters Professional Open Source™  A particularly useful method is setEntity(), which lets you bind a persistent entity .  session.createQuery("from Item item where item.seller = :seller")  .setEntity("seller", theSeller);  However, there is also a generic method that allows you to bind an argument of any Hibernate type:© JBoss, Inc. 2003, 2004. 6
  7. 7. Professional Open Source™© JBoss, Inc. 2003, 2004. 7
  8. 8. Using positional parameters Professional Open Source™© JBoss, Inc. 2003, 2004. 8
  9. 9. Setting query hints Professional Open Source™ What does these hints specify?© JBoss, Inc. 2003, 2004. 9
  10. 10. Professional Open Source™© JBoss, Inc. 2003, 2004. 10
  11. 11. Listing all results Professional Open Source™  In Hibernate, the list() method executes the query and returns the results as a java.util.List:  List result = myQuery.list();  List result = myCriteria.list();  With some queries you know that the result is only a single instance— for example, if you want only the highest bid.  In this case, you can read it from the result list by index, result.get(0). Or, you can limit the number of returned rows with setMaxResult(1). Then you may execute the query with the uniqueResult()  method, because you know only one object will be returned:© JBoss, Inc. 2003, 2004. 11
  12. 12. Iterating through the results Professional Open Source™  The Hibernate Query interface also provides the iterate() method to execute a query. It returns the same data as list(), but relies on a different strategy for retrieving the results.  When you call iterate() to execute a query, Hibernate retrieves only the primary key (identifier) values of entity objects in a first SQL SELECT, and then tries to find the rest of the state of the objects in the persistence context cache, and (if enabled) the second-level cache.  Consider the following code: This query results in execution of at least one SQL SELECT, with all columns of the CATEGORY table included in the SELECT clause:© JBoss, Inc. 2003, 2004. 12
  13. 13. Professional Open Source™ The initial query retrieves only Category primary key values. You then iterate through the result; Hibernate looks up each Category object in the current persistence context and, if enabled, in the second-level cache. If a cache miss occurs, Hibernate executes an additional SELECT for each turn, retrieving the full Category object by its primary key from the database. Hibernate keeps the iterator open until you finish iteration through all results or until the Session is closed. You can also close it explicitly with org.hibernate.Hibernate.close(iterator).© JBoss, Inc. 2003, 2004. 13
  14. 14. Scrolling with database cursors Professional Open Source™  Plain JDBC provides a feature called scrollable resultsets. This technique uses a cursor that is held on the database management system.  The cursor points to a particular row in the result of a query, and the application can move the cursor forward and backward. You can even jump to a particular row with the cursor.© JBoss, Inc. 2003, 2004. 14
  15. 15. Scrolling with database cursors Professional Open Source™ The ScrollMode constants of the Hibernate API are equivalent to the constants in plain JDBC.© JBoss, Inc. 2003, 2004. 15
  16. 16. Using named queries Professional Open Source™  Hibernate lets you externalize query strings to the mapping  metadata, a technique that is called named queries.  In Hibernate, the getNamedQuery() method obtains a Query instance for a named query:  session.getNamedQuery("findItemsByDescription")  .setString("desc", description);© JBoss, Inc. 2003, 2004. 16
  17. 17. Defining a named query in XML metadata Professional Open Source™  You can place a named query inside any <hibernate-mapping> element in your XML metadata. If you place a named query definition inside a <class> element, instead of the root, it’s prefixed with the name of the entity class; for example, findItemsByDescription is then callable as auction.model.Item.findItemsByDescription.© JBoss, Inc. 2003, 2004. 17
  18. 18. Setting query hints declaratively Professional Open Source™© JBoss, Inc. 2003, 2004. 18
  19. 19. Selection Professional Open Source™  Simplest query is :  from Item  from Item as item  from Item item  This query generates the following SQL:  select i.ITEM_ID, i.NAME, i.DESCRIPTION, ... from ITEM i© JBoss, Inc. 2003, 2004. 19
  20. 20. Polymorphic queries Professional Open Source™  from BillingDetails  from java.lang.Object  from java.io.Serializable© JBoss, Inc. 2003, 2004. 20
  21. 21. Restriction Professional Open Source™  The WHERE clause is used to express a restriction in HQL  from User u where u.email = foo@hibernate.org  Comparison expressions And ,or usage© JBoss, Inc. 2003, 2004. 21
  22. 22. Expressions with collections Professional Open Source™  from Item i where i.bids is not empty  You can also express that you require a particular element to be present in a collection:  from Item i, Category c where i.id = 123 and i member of c.items© JBoss, Inc. 2003, 2004. 22
  23. 23. Calling functions Professional Open Source™  from User u where lower(u.email) = foo@hibernate.org‘  from User user where concat(user.firstname, user.lastname) like G% K%‘  from Item i where size(i.bids) > 3© JBoss, Inc. 2003, 2004. 23
  24. 24. HQL functions Professional Open Source™© JBoss, Inc. 2003, 2004. 24
  25. 25. Ordering query results Professional Open Source™  from User u order by u.username  from User u order by u.lastname asc, u.firstname asc© JBoss, Inc. 2003, 2004. 25
  26. 26. Projection Professional Open Source™  The SELECT clause performs projection in HQL It allows you to specify exactly which objects or properties of objects you need in the query result.  Consider the following code : This query returns a List of Object[]. At index 0 is the Item, and at index 1 is the Bid. Because this is a product, the result contains every possible combination of Item and Bid rows found in the two underlying tables. The following explicit SELECT clause also returns a collection of Object[]s:© JBoss, Inc. 2003, 2004. 26
  27. 27. Getting distinct results Professional Open Source™© JBoss, Inc. 2003, 2004. 27
  28. 28. Calling functions Professional Open Source™  select item.startDate, current_date() from Item item  select item.startDate, item.endDate, upper(item.name)  from Item item© JBoss, Inc. 2003, 2004. 28
  29. 29. Joining relations and associations Professional Open Source™  If you join tables ITEM and BID with an inner join, using their common  attributes (the ITEM_ID column), you get all items and their bids in a new result table. Note that the result of this operation contains only items that have bids. If you want all items, and NULL values instead of bid data when there is no corresponding bid, you use a (left) outer join,© JBoss, Inc. 2003, 2004. 29
  30. 30. Inner Join Professional Open Source™© JBoss, Inc. 2003, 2004. 30
  31. 31. Left outer join Professional Open Source™© JBoss, Inc. 2003, 2004. 31
  32. 32. HQL join options Professional Open Source™ – An implicit association join – An ordinary join in the FROM clause – A fetch join in the FROM clause – A theta-style join in the WHERE clause© JBoss, Inc. 2003, 2004. 32
  33. 33. Implicit association joins Professional Open Source™  from User u where u.homeAddress.city = Bangkok‘  select distinct u.homeAddress.city from User u  from Bid bid where bid.item.description like %Foo%‘  from Bid bid where bid.item.category.name like Laptop%  from Bid bid  where bid.item.category.name like Laptop%  and bid.item.successfulBid.amount > 100© JBoss, Inc. 2003, 2004. 33
  34. 34. Joins expressed in the FROM clause Professional Open Source™  from Item I join i.bids b  where i.description like %Foo%  and b.amount > 100  The resulting SQL is:  select i.DESCRIPTION, i.INITIAL_PRICE, ...  b.BID_ID, b.AMOUNT, b.ITEM_ID, b.CREATED_ON  from ITEM i  inner join BID b on i.ITEM_ID = b.ITEM_ID  where i.DESCRIPTION like %Foo%  and b.AMOUNT > 100© JBoss, Inc. 2003, 2004. 34
  35. 35. Professional Open Source™  select i  from Item i join i.bids b  where i.description like %Foo%  and b.amount > 100  select i  from Item i in(i.bids) b  where i.description like %Foo%  and b.amount > 100  Are these both queries same?  The from Item i in(i.bids) b results in the same inner join as the earlier example with from Item i join i.bids b.© JBoss, Inc. 2003, 2004. 35
  36. 36. Outer Join Professional Open Source™  from Item i  left join i.bids b  with b.amount > 100  where i.description like %Foo%© JBoss, Inc. 2003, 2004. 36
  37. 37. Dynamic fetching strategies with join Professional Open Source™  from Item i  left join fetch i.bids  where i.description like %Foo%‘  If u use fetch in HQL, the collection is eagerly fetched.© JBoss, Inc. 2003, 2004. 37
  38. 38. Theta-style joins Professional Open Source™  from User, Category  from User user, LogRecord log where user.username = log.username  The join condition here is a comparison of username, present as an attribute in both classes. If both rows have the same username, they’re joined (with an inner join) in the result.© JBoss, Inc. 2003, 2004. 38
  39. 39. Comparing identifiers Professional Open Source™  from Item i, User u  where i.seller = u and u.username = steve‘  This is same as follows with join :  from Item i join i.seller u  where u.username = steve© JBoss, Inc. 2003, 2004. 39
  40. 40. Reporting queries Professional Open Source™  select count(i) from Item i  select count(i.successfulBid) from Item i  select sum(i.successfulBid.amount) from Item i  select min(bid.amount), max(bid.amount)  from Bid bid where bid.item.id = 1  select count(distinct i.description) from Item i© JBoss, Inc. 2003, 2004. 40
  41. 41. Grouping aggregated results Professional Open Source™  select u.lastname, count(u) from User u  group by u.lastname  select bid.item.id, avg(bid.amount) from Bid bid  group by bid.item.id  select bid.item.id, count(bid), avg(bid.amount)  from Bid bid  where bid.item.successfulBid is null  group by bid.item.id© JBoss, Inc. 2003, 2004. 41
  42. 42. Restricting groups with having Professional Open Source™  select user.lastname, count(user)  from User user  group by user.lastname  having user.lastname like A%  select item.id, count(bid), avg(bid.amount)  from Item item  join item.bids bid  where item.successfulBid is null  group by item.id  having count(bid) > 10© JBoss, Inc. 2003, 2004. 42
  43. 43. Utilizing dynamic instantiation Professional Open Source™  select new ItemBidSummary(  bid.item.id, count(bid), avg(bid.amount)  )  from Bid bid  where bid.item.successfulBid is null  group by bid.item.id© JBoss, Inc. 2003, 2004. 43
  44. 44. Using subselects Professional Open Source™  from User u where 10 < (  select count(i) from u.items i where i.successfulBid is not null )  from Bid bid where bid.amount + 1 >= (  select max(b.amount) from Bid b )© JBoss, Inc. 2003, 2004. 44
  45. 45. Quantification Professional Open Source™  from Item i where 100 > all ( select b.amount from i.bids b )  from Item i where 100 <= any ( select b.amount from i.bids b )  from Item i where 100 = some ( select b.amount from i.bids b )  from Item i where 100 in ( select b.amount from i.bids b )© JBoss, Inc. 2003, 2004. 45
  46. 46. Professional Open Source™  from Sale sale  where sale.date > :startDate  left join fetch sale.product  session.createCriteria(Sale.class) .setFetchMode("product",FetchMode.EAGER) .list();© JBoss, Inc. 2003, 2004. 46
  47. 47. Professional Open Source™  from Shirt shirt join shirt.availableSizes size  where size.number > 40  session.createCriteria(Shirt.class) .  createCriteria("availableSizes") .  add(Expression.gt("number", new Integer(40))) .list();  session.createCriteria(Shirt.class) .  createAlias("availableSizes","size") .add(Expression.gt("size.number", new Integer(40))) .list();© JBoss, Inc. 2003, 2004. 47

×