`

Hql 语法

阅读更多

HQL是完全面向对象的查询语言,因此可以支持继承和多态等特征。
HQL查询依赖于Query类,每个Query实例对应一个查询对象,使用HQL查询按
如下步骤进行:
(1)获取Hibernate Session对象;
(2)编写HQL语句;
(3)以HQL语句作为参数,调用Session的createQuery方法创建查询对象;
(4)如果HQL语句包含参数,调用Query的setXxx方法为参数赋值;
(5)调用Query对象的list等方法遍历查询结果。
查询示例:

public class HqlQuery
  {
      public static void main(String[] args) throws Exception {
         HqlQuery mgr = new HqlQuery();
         //调用查询方法
         mgr.findPersons();
         //调用第二个查询方法
         mgr.findPersonByHappenDate();
         HibernateUtil.sessionFactory.close();
     }
     //第一个查询方法
      private void findPersons() {
         //获得Hibernate Session
         Session sess = HibernateUtil.currentSession();
         //开始事务
         Transaction tx = sess.beginTransaction();
         //以HQL语句创建Query对象
         //执行setString方法为HQL语句的参数赋值
         //Query调用list方法访问查询的全部实例
         List p1 = sess.createQuery("from Person p where o.myEvents.title = :
             eventTitle").setString("eventTitle", "很普通事情").list();
         //遍历查询的全部结果
         for (Iterator pit = p1.iterator(); pit.haxNext(); )
          {
             Person p = (Person)pit.next();
             System.out.println(p.getName());
         }
         //提交事务
         tx.commit();
         HibernateUtil.closeSession();
     }
     //第二个查询方法
      private void findPersonByHappenDate() throws Exception {
         Session sess = HibernateUtil.currentSession();
         Transaction tx = sess.beginTransaction();
         //解析出Date对象
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         Date start = sdf.parse("2007-11-27");
         System.out.println("系统开始通过日期查找人" + start);
         //通过Session的createQuery方法创建Query对象
         //设置参数
         //返回结果集
         List pl = sess.createQuery(
             "from Person p where p.myEvents.happenDate between :firstDate
             and :endDate")
                         .setDate("firstDate", start)
                         .setDate("endDate", new Date())
                         .list();
         //遍历结果集
         for (Iterator pit = pl.iterator(); pit.hasNext(); )
          {
             Person p = (Person)pit.next();
             System.out.println(p.getName());
         }
         tx.commit();
         HibernateUtil.closeSession();
     }
} 
 



$下面介绍HQL语句的语法
1.from子句
from Person
表明从Person持久化类中选出全部的实例。
推荐:from Person as p


2.select子句

select p.name from Person as p
select p.name.firstName from Person as p
select new list(p.name, p.address) from Person as p
select new ClassTest(p.name, p.address) from Person as p (有前提)
select p.name as personName from Person as p
select new map(p.name as personName) from Person as p (与new map()结合更普遍) 
 



3.聚集函数

avg,count,max,min,sum
select count(*) from Person
select max(p.age) from Person as p
select p.name || "" || p.address from Person as p 
 



4.多态查询

from Person as p
from java.lang.Object o
from Named as n 
 



5.where子句

from Person where name like "tom%"
from Person as p where p.name like "tom%"
from Cat cat where cat.mate.name like "kit%"
     select * from cat_table as table1 cat_table as table2 where table1.mate =
     table2.id and table1.name like "kit%"
from Foo foo where foo.bar.baz.customer.address.city like "fuzhou%"
from Cat cat, Cat rival where cat.mate = rival.mate
select cat, mate
from Cat cat, Cat mate
where cat.mate = mate
from Cat as cat where cat.id = 123
from Cat as cat where cat.mate.id = 69
from Person as person
where person.id.country = 'AU'
     and person.id.medicareNumber = 123456
from Account as account
where account.owner.id.country = 'AU'
     and account.owner.id.medicareNumber = 123456
from Cat cat where cat.class = DomesticCat
from Account as a where a.person.name.firstName like "dd%" // 正确
from Account as a where a.person.name like "dd%" // 错误 
 



6.表达式

from DomesticCat cat where cat.name between 'A' and 'B'
from DomesticCat cat where cat.name in ('Foo', 'Bar', 'Baz')
from DomesticCat cat where cat.name not between 'A' and 'B'
from DomesticCat cat where cat.name not in ('Foo', 'Bar', 'Baz')
from DomesticCat cat where cat.name is null
from Person as p where p.address is not null
<property name="hibernate.query.substitutions">true 1, false 0</property>
from Cat cat where cat.alive = true
from Cat cat where cat.kittens.size > 0
from Cat cat where size(cat.kittens) > 0
from Calendar cal where maxelement(cal.holidays) > current date
from Order order where maxindex(order.items) > 100
from Order order where minelement(order.items) > 10000 
 
//操作集合元素
select mother from Cat as mother, Cat as kit
where kit in elements(foo.kittens)
//p的name属性等于集合中某个元素的name属性
select p from NameList list, Person p
where p.name = some elements(list.names)
//操作集合元素
from Cat cat where exists elements(cat.kittens)
from Player p where 3 > all elements(p.scores)
from Show show where 'fizard' in indices(show.acts)
//items是有序集合属性,items[0]代表第一个元素
from Order order where order.items[0].id = 1234
//holidays是map集合属性,holidays[national day]是代表其中第一个元素
select person from Person person, Calendar calendar
where calendar.holidays['national day'] = person.birthDay
     and person.nationality.calendar = calendar
//下面同时使用list集合和map集合属性
select item from Item item, Order order
where order.items[order.deliveredItemIndices[0]] = item and order.id = 11
select item from Item item, Order order
where order.items[maxindex(order.items)] = item and order.id = 11

select item from Item item, Order order
where order.items[size(order.items) - 1] = item

select cust
from Product prod,
     Store store
     inner join store.customers cust
where prod.name = 'widget'
     and store.location.name in ['Melbourne', 'Sydney']
     and prod = all elements(cust.currentOrder.lineItems)

SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order
FROM customers cust,
     stores store,
     locations loc,
     store_customers sc,
     product prod
WHERE prod.name = 'widget'
     AND store.loc_id = loc.id
     AND loc.name IN ('Melbourne', 'Sydney')
     AND sc.store_id = store.id
     AND sc.cust_id = cust.id
     AND prod.id = ALL(
         SELECT item.prod_id
         FROM line_items item, orders o
         WHERE item.order_id = o.id
             AND cust.current_order = o.id
     )
 



7.order by子句

from Person as p
order by p.name, p.age
from Person as p
order by p.name asc, p.age desc 
 



8.group by子句

select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color
//select后出现的id处出现在group by之后,而name属性则出现在聚集函数中
select foo.id, avg(name), max(name)
from Foo foo join foo.names name
group by foo.id

select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color
having cat.color in (eg.Color.TABBY, eg.Color.BLACK)

select cat
from Cat cat
join cat.kittens kitten
group by cat
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc 
 



9.子查询

from Cat as fatcat
where fatcat.weight > (select avg(cat.weight) from DomesticCat cat)

from Cat as cat
where not (cat.name, cat.color) in (
     select cat.name, cat.color from DomesticCat cat
) 
 



10.fetch关键字

from Person as p join p.scores

from Document fetch all properties order by name
from Document doc fetch all properties where lower(doc.name) like '%cat%' 
 



11.命名查询

<!--定义命名查询-->
<query name="myNamedQuery">
     <!--此处确定命名查询的HQL语句-->
     from Person as p where p.age > ?
</query> 

<!--sql-->
<sql-query name="myNamedQuery"><![CDATA[
       select {c.*} from CUSTOMERS c where c.NAME like: name
    ]]>
    <return alias="c" class="Customer"/>
</sql-query>
 



调用命名查询的示例代码如下:

private void findByNamedQuery() throws Exception {
     Session session = HibernateUtil.currentSession();
     Transaction tx = session.beginTransaction();
     System.out.println("执行命名查询");
     //调用命名查询
     List pl = sess.getNamedQuery("myNamedQuery")
                                     //为参数赋值
                                     .setInteger(0, 20)
                                     //返回全部结果
                                     .list();
     //遍历结果集
     for (Integer pit = pl.iterator(); pit.hasNext(); )
      {
         Person p = (Person)pit.next();
         System.out.println(p.getName());
     }
     tx.commit();
     HibernateUtil.closeSession();
} 
 

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    HQL语法大全,并带有详细的例子

    ### HQL语法详解及其应用案例 #### 一、HQL简介 HQL(Hibernate Query Language)是一种面向对象的查询语言,被广泛应用于Hibernate框架中,用于执行数据持久化操作。与传统的SQL相比,HQL更加面向对象,支持诸如...

    HQL语法入门学习HQL语法入门学习

    在深入探讨HQL语法之前,我们首先需要理解什么是HQL。HQL,全称为Hibernate Query Language,是Hibernate框架提供的一种面向对象的查询语言。与SQL(Structured Query Language)不同,HQL是专为ORM(Object-...

    HQL 语法总结 实体查询

    ### HQL语法总结:实体查询详解 #### 一、实体查询概述 HQL(Hibernate Query Language)是一种面向对象的查询语言,它允许开发者以一种类似于SQL但更接近于面向对象的方式来编写查询。本文将详细介绍HQL中的实体...

    J2EE HQL语法大全

    **J2EE HQL语法大全** 在Java企业级开发中,J2EE(Java 2 Platform, Enterprise Edition)是广泛采用的技术平台,它提供了一整套标准和框架,用于构建可扩展、分布式的企业级应用程序。在J2EE环境中,Hibernate作为...

    强烈建议的HQL语法规则详解

    2. **编写HQL语句**:HQL的语法类似于SQL,但更注重对象。例如,`from Person p where p.myEvents.title = :eventTitle`这样的查询语句会找出所有`myEvents`标题为`eventTitle`的`Person`对象。 3. **创建Query对象*...

    Hibernate hql查询语法总结

    《Hibernate HQL查询语法详解》 Hibernate,作为Java领域中广泛应用的对象关系映射(ORM)框架,极大地简化了数据库操作。其内置的HQL(Hibernate Query Language)是一种面向对象的查询语言,它允许开发者以类和...

    HQL查询及语法

    2. **编写HQL语句**:根据需求构建HQL查询语句,这一步骤需要熟悉HQL语法结构。 3. **创建Query对象**:利用Session对象的`createQuery`方法,传入HQL语句创建Query实例。 4. **设置参数**:如果HQL语句中包含...

    HQL语句的语法

    HQL语句的语法结构与SQL相似,但更注重对象和类的概念。以下将详细介绍HQL语句的几个关键部分: 1. **from 子句**:这是HQL查询的起点,用于指定要查询的持久化类。例如,`from Person as p`表示从`Person`类中选择...

    hql查询语言语法

    #### 四、HQL语法详解 接下来,我们将详细介绍HQL的一些关键语法。 ##### 1. `from`子句 - **基本格式**:`from [类名] [别名]` - **示例**:`from Person p`,表示从`Person`类中选取所有的实例。 - **扩展**:...

    Spring中常用的hql查询方法

    ### Spring框架中HQL查询方法详解 在Spring框架与Hibernate技术结合使用时,HQL(Hibernate Query Language)作为对象查询语言被广泛应用于数据查询操作之中。本文将详细解析Spring框架中常用的HQL查询方法及其应用...

    03-HQL实用技术.pdf

    - **编写HQL语句**: 编写符合HQL语法的查询语句。 - **创建Query对象**: 使用`Session.createQuery()`方法创建`Query`对象。 - **执行查询**: 调用`Query`对象的`list()`方法执行查询并获取结果集。 **2.3 HQL支持...

    Hibernate教程(数据查询)HQL,PDF格式

    这条语句使用HQL语法查询了所有的`User`对象。`find`方法是`Session`接口的一个快捷方法,用于执行HQL查询。这里,查询字符串"from User"告诉Hibernate检索`User`类的所有实例。 #### HQL查询的灵活性 HQL不仅支持...

    HQL语句大全HQL语句大全

    HQL语法接近于SQL但又有所不同,它允许开发者以面向对象的方式来表达查询逻辑,使得查询更加直观且易于理解。 #### 二、HQL的基本用法 1. **获取Hibernate Session** - 在执行任何HQL查询之前,首先需要通过`...

    hql批量删除

    在Hibernate中,批量插入的HQL语法与标准的SQL语法有所不同,它只支持从一个表中通过select语句选择数据,并将这些数据插入到另一个表中。这在SQL中通常称为“insert into ... select ...”。 举例来说,如果想要将...

    hibernate -HQL

    #### HQL语法概览 HQL的完整语法结构包括以下几个关键部分:`select`, `update`, `delete`, `from`, `where`, `group by`, `having`, `order by`。值得注意的是,`update` 和 `delete` 操作是在Hibernate 3版本中...

    Hibernate数据检索(HQL)笔记

    - **简洁性**:HQL 的语法比 SQL 更简洁,易于编写和理解。 - **灵活性**:支持复杂的查询表达式,如分组、排序等。 ##### 2. HQL 查询示例 - **查找特定条件下的对象**: - **示例1**:查找姓名为“张三”的用户...

    weblogic10.3 org.hibernate.hql.ast.HqlToken报错问题

    总之,解决“weblogic10.3 org.hibernate.hql.ast.HqlToken报错”问题需要对Hibernate和WebLogic有深入的理解,以及对HQL语法的熟练掌握。通过逐步排查和测试,通常能找到问题的根源并成功解决。同时,保持软件更新...

    关于HQL相关的论文

    1. **语法规则**:HQL语法与SQL有许多相似之处,如查询、选择、排序等,但主要的区别在于HQL以类和属性为操作对象,而SQL以表和字段为主。例如,`from Employee as e`相当于SQL中的`select * from Employee`。 2. *...

    hql语句查询

    #### 三、HQL语法详解 ##### 1. 基础查询 - **查询所有列**: ```hql SELECT obj FROM TableName obj; ``` - **查询指定列**: ```hql SELECT obj.column1, obj.column2 FROM TableName obj; ``` ##### 2. ...

Global site tag (gtag.js) - Google Analytics