HQL查询及语法

来源:互联网 发布:淘宝李白凤求凰可信吗 编辑:程序博客网 时间:2024/04/29 20:27
Java代码  收藏代码
  1. HQL:Hibernate Query Language  
  2. HQL是完全面向对象的查询语言,因此可以支持继承和多态等特征。  
  3. HQL查询依赖于Query类,每个Query实例对应一个查询对象,使用HQL查询按  
  4. 如下步骤进行:  
  5. (1)获取Hibernate Session对象;  
  6. (2)编写HQL语句;  
  7. (3)以HQL语句作为参数,调用Session的createQuery方法创建查询对象;  
  8. (4)如果HQL语句包含参数,调用Query的setXxx方法为参数赋值;  
  9. (5)调用Query对象的list等方法遍历查询结果。  
  10. 查询示例:  
  11. public class HqlQuery  
  12. ...{  
  13.     public static void main(String[] args) throws Exception ...{  
  14.         HqlQuery mgr = new HqlQuery();  
  15.         //调用查询方法  
  16.   
  17.         mgr.findPersons();  
  18.         //调用第二个查询方法  
  19.   
  20.         mgr.findPersonByHappenDate();  
  21.         HibernateUtil.sessionFactory.close();  
  22.     }  
  23.     //第一个查询方法  
  24.   
  25.     private void findPersons() ...{  
  26.         //获得Hibernate Session  
  27.   
  28.         Session sess = HibernateUtil.currentSession();  
  29.         //开始事务  
  30.   
  31.         Transaction tx = sess.beginTransaction();  
  32.         //以HQL语句创建Query对象  
  33.   
  34.         //执行setString方法为HQL语句的参数赋值  
  35.   
  36.         //Query调用list方法访问查询的全部实例  
  37.   
  38.         List p1 = sess.createQuery("from Person p where o.myEvents.title = :  
  39.             eventTitle").setString("eventTitle", "很普通事情").list();  
  40.         //遍历查询的全部结果  
  41.   
  42.         for (Iterator pit = p1.iterator(); pit.haxNext(); )  
  43.         ...{  
  44.             Person p = (Person)pit.next();  
  45.             System.out.println(p.getName());  
  46.         }  
  47.         //提交事务  
  48.   
  49.         tx.commit();  
  50.         HibernateUtil.closeSession();  
  51.     }  
  52.     //第二个查询方法  
  53.   
  54.     private void findPersonByHappenDate() throws Exception ...{  
  55.         Session sess = HibernateUtil.currentSession();  
  56.         Transaction tx = sess.beginTransaction();  
  57.         //解析出Date对象  
  58.   
  59.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  60.         Date start = sdf.parse("2007-11-27");  
  61.         System.out.println("系统开始通过日期查找人" + start);  
  62.         //通过Session的createQuery方法创建Query对象  
  63.   
  64.         //设置参数  
  65.   
  66.         //返回结果集  
  67.   
  68.         List pl = sess.createQuery(  
  69.             "from Person p where p.myEvents.happenDate between :firstDate  
  70.             and :endDate")  
  71.                         .setDate("firstDate", start)  
  72.                         .setDate("endDate"new Date())  
  73.                         .list();  
  74.         //遍历结果集  
  75.   
  76.         for (Iterator pit = pl.iterator(); pit.hasNext(); )  
  77.         ...{  
  78.             Person p = (Person)pit.next();  
  79.             System.out.println(p.getName());  
  80.         }  
  81.         tx.commit();  
  82.         HibernateUtil.closeSession();  
  83.     }  
  84. }  
  85.   
  86. $下面介绍HQL语句的语法  
  87. 1.from子句  
  88. from Person  
  89. 表明从Person持久化类中选出全部的实例。  
  90. 推荐:from Person as p  
  91.   
  92. 2.select子句  
  93. select p.name from Person as p  
  94. select p.name.firstName from Person as p  
  95. select new list(p.name, p.address) from Person as p  
  96. select new ClassTest(p.name, p.address) from Person as p (有前提)  
  97. select p.name as personName from Person as p  
  98. select new map(p.name as personName) from Person as p (与new map()结合更普遍)  
  99.   
  100. 3.聚集函数  
  101. avg,count,max,min,sum  
  102. select count(*) from Person  
  103. select max(p.age) from Person as p  
  104. select p.name || "" || p.address from Person as p  
  105.   
  106. 4.多态查询  
  107. from Person as p  
  108. from java.lang.Object o  
  109. from Named as n  
  110.   
  111. 5.where子句  
  112. from Person where name like "tom%"  
  113. from Person as p where p.name like "tom%"  
  114. from Cat cat where cat.mate.name like "kit%"  
  115.     select * from cat_table as table1 cat_table as table2 where table1.mate =  
  116.     table2.id and table1.name like "kit%"  
  117. from Foo foo where foo.bar.baz.customer.address.city like "fuzhou%"  
  118. from Cat cat, Cat rival where cat.mate = rival.mate  
  119. select cat, mate  
  120. from Cat cat, Cat mate  
  121. where cat.mate = mate  
  122. from Cat as cat where cat.id = 123  
  123. from Cat as cat where cat.mate.id = 69  
  124. from Person as person  
  125. where person.id.country = 'AU'  
  126.     and person.id.medicareNumber = 123456  
  127. from Account as account  
  128. where account.owner.id.country = 'AU'  
  129.     and account.owner.id.medicareNumber = 123456  
  130. from Cat cat where cat.class = DomesticCat  
  131. from Account as a where a.person.name.firstName like "dd%" // 正确  
  132.   
  133. from Account as a where a.person.name like "dd%" // 错误  
  134.   
  135.   
  136. 6.表达式  
  137. from DomesticCat cat where cat.name between 'A' and 'B'  
  138. from DomesticCat cat where cat.name in ('Foo''Bar''Baz')  
  139. from DomesticCat cat where cat.name not between 'A' and 'B'  
  140. from DomesticCat cat where cat.name not in ('Foo''Bar''Baz')  
  141. from DomesticCat cat where cat.name is null  
  142. from Person as p where p.address is not null  
  143. <property name="hibernate.query.substitutions">true 1false 0</property>  
  144. from Cat cat where cat.alive = true  
  145. from Cat cat where cat.kittens.size > 0  
  146. from Cat cat where size(cat.kittens) > 0  
  147. from Calendar cal where maxelement(cal.holidays) > current date  
  148. from Order order where maxindex(order.items) > 100  
  149. from Order order where minelement(order.items) > 10000  
  150. //操作集合元素  
  151.   
  152. select mother from Cat as mother, Cat as kit  
  153. where kit in elements(foo.kittens)  
  154. //p的name属性等于集合中某个元素的name属性  
  155.   
  156. select p from NameList list, Person p  
  157. where p.name = some elements(list.names)  
  158. //操作集合元素  
  159.   
  160. from Cat cat where exists elements(cat.kittens)  
  161. from Player p where 3 > all elements(p.scores)  
  162. from Show show where 'fizard' in indices(show.acts)  
  163. //items是有序集合属性,items[0]代表第一个元素  
  164.   
  165. from Order order where order.items[0].id = 1234  
  166. //holidays是map集合属性,holidays[national day]是代表其中第一个元素  
  167.   
  168. select person from Person person, Calendar calendar  
  169. where calendar.holidays['national day'] = person.birthDay  
  170.     and person.nationality.calendar = calendar  
  171. //下面同时使用list集合和map集合属性  
  172.   
  173. select item from Item item, Order order  
  174. where order.items[order.deliveredItemIndices[0]] = item and order.id = 11  
  175. select item from Item item, Order order  
  176. where order.items[maxindex(order.items)] = item and order.id = 11  
  177.   
  178. select item from Item item, Order order  
  179. where order.items[size(order.items) - 1] = item  
  180.   
  181. select cust  
  182. from Product prod,  
  183.     Store store  
  184.     inner join store.customers cust  
  185. where prod.name = 'widget'  
  186.     and store.location.name in ['Melbourne''Sydney']  
  187.     and prod = all elements(cust.currentOrder.lineItems)  
  188.   
  189. SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order  
  190. FROM customers cust,  
  191.     stores store,  
  192.     locations loc,  
  193.     store_customers sc,  
  194.     product prod  
  195. WHERE prod.name = 'widget'  
  196.     AND store.loc_id = loc.id  
  197.     AND loc.name IN ('Melbourne''Sydney')  
  198.     AND sc.store_id = store.id  
  199.     AND sc.cust_id = cust.id  
  200.     AND prod.id = ALL(  
  201.         SELECT item.prod_id  
  202.         FROM line_items item, orders o  
  203.         WHERE item.order_id = o.id  
  204.             AND cust.current_order = o.id  
  205.     )  
  206.   
  207. 7.order by子句  
  208. from Person as p  
  209. order by p.name, p.age  
  210. from Person as p  
  211. order by p.name asc, p.age desc  
  212.   
  213. 8.group by子句  
  214. select cat.color, sum(cat.weight), count(cat)  
  215. from Cat cat  
  216. group by cat.color  
  217. //select后出现的id处出现在group by之后,而name属性则出现在聚集函数中  
  218.   
  219. select foo.id, avg(name), max(name)  
  220. from Foo foo join foo.names name  
  221. group by foo.id  
  222.   
  223. select cat.color, sum(cat.weight), count(cat)  
  224. from Cat cat  
  225. group by cat.color  
  226. having cat.color in (eg.Color.TABBY, eg.Color.BLACK)  
  227.   
  228. select cat  
  229. from Cat cat  
  230. join cat.kittens kitten  
  231. group by cat  
  232. having avg(kitten.weight) > 100  
  233. order by count(kitten) asc, sum(kitten.weight) desc  
  234.   
  235. 9.子查询  
  236. from Cat as fatcat  
  237. where fatcat.weight > (select avg(cat.weight) from DomesticCat cat)  
  238.   
  239. from Cat as cat  
  240. where not (cat.name, cat.color) in (  
  241.     select cat.name, cat.color from DomesticCat cat  
  242. )  
  243.   
  244. 10.fetch关键字  
  245. from Person as p join p.scores  
  246.   
  247. from Document fetch all properties order by name  
  248. from Document doc fetch all properties where lower(doc.name) like '%cat%'  
  249.   
  250. 11.命名查询  
  251. <!--定义命名查询-->  
  252. <query name="myNamedQuery">  
  253.     <!--此处确定命名查询的HQL语句-->  
  254.     from Person as p where p.age > ?  
  255. </query>  
  256.   
  257. 调用命名查询的示例代码如下:  
  258. private void findByNamedQuery() throws Exception ...{  
  259.     Session session = HibernateUtil.currentSession();  
  260.     Transaction tx = session.beginTransaction();  
  261.     System.out.println("执行命名查询");  
  262.     //调用命名查询  
  263.   
  264.     List pl = sess.getNamedQuery("myNamedQuery")  
  265.                                     //为参数赋值  
  266.   
  267.                                     .setInteger(020)  
  268.                                     //返回全部结果  
  269.   
  270.                                     .list();  
  271.     //遍历结果集  
  272.   
  273.     for (Integer pit = pl.iterator(); pit.hasNext(); )  
  274.     ...{  
  275.         Person p = (Person)pit.next();  
  276.         System.out.println(p.getName());  
  277.     }  
  278.     tx.commit();  
  279.     HibernateUtil.closeSession();  
  280. }    

 原文出处:http://mxdxm.iteye.com/blog/1056237