`
f910230
  • 浏览: 5487 次
  • 性别: Icon_minigender_1
  • 来自: 南京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

HQL:Hibernate Query Language

阅读更多

HQL:Hibernate Query Language
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>
调用命名查询的示例代码如下:
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(Hibernate Query Language):

    HQL(Hibernate Query Language):是面向对象的查询语句,它的语法和SQL语句有些相像,在运行时才得以解析.HQL并不像SQL那样是.

    Hibernate Query Language

    Hibernate Query Language 培训教材

    Hibernate Query Language基础使用详解

    讲解如何使用HQL,包括基本的操作和进阶用的高级使用

    Hibernate Tutorial 09 Hibernate Query Language

    HQL is database independent and translated into SQL by Hibernate at runtime. When writing HQL, we can concentrate on the objects and properties without knowing much detail on the underlying database. ...

    JDBC与Hibernate区别

    ◆使用的SQL语言不同:JDBC使用的是基于关系型数据库的标准SQL语言,Hibernate使用的是HQL(Hibernate query language)语言 ◆操作的对象不同:JDBC操作的是数据,将数据通过SQL语句直接传送到数据库中执行,...

    hibernate中的hql查询案例

    HQL(Hibernate Query Language),提供更加丰富灵活、更为强大的查询能力;HQL更接近SQL语句查询语法。查询的表(Table)名称是类的名称,表的字段是对象的属性,有多个类的话,可以使用类的全限定名来指定,比如...

    Hibernate_Query_Language基础认识.rar

    Hibernate_Query_Language基础认识,主要是使用了一些HQL的特性,用idea搭建,适合小白上手

    hibernate操作数据库笔记

    一.使用Hibernate的Session对象操作数据库 1.初始化Hibernate:在要使用Hibernate的类的方法中实例化Configuration对象并用Configuration对象的configure()方法将hibernate... //HQL(Hibernate Query Language)语句查询

    MyEclipse中hibernate的配置

    和JDBC比较一下,同样都是数据库中间件(DM,Database Middleware),JDBC利用SQL语言操作的是数据,而Hibernate则是利用自己的查询语言Hibernate Query Language(HQL虽然底层还是要转换成sql语言)操作的是持久化对象...

    HQL查询语言的使用介绍

    HQL是Hibernate Query Language的缩写,语法很想SQL,但是HQL是一种面向对象的查询语言。SQL的操作对象是数据列、表等数据库对象,而HQL操作的是类、实例、属性

    Hibernate Recipes A Problem-Solution Approach

    How to use Hibernate Query Language (HQL) How to perform batch processing and use native SQL, criteria queries, caching objects, and more How to enable Hibernate in web applications with e-commerce ...

    hibernate.properties

    #hibernate.query.factory_class org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory ################# ### Platforms ### ################# ## JNDI Datasource #hibernate.connection....

    Hibernate Reference Documentation3.1

    14. HQL: The Hibernate Query Language 14.1. Case Sensitivity 14.2. The from clause 14.3. Associations and joins 14.4. Forms of join syntax 14.5. The select clause 14.6. Aggregate functions 14.7. ...

    hibernate 教程

    Hibernate查询语言(Query Language), 即HQL 11.1. 大小写敏感性(Case Sensitivity) 11.2. from 子句 11.3. 联合(Associations)和连接(joins) 11.4. select子句 11.5. 统计函数(Aggregate ...

    hibernate总结

    2. 通过HQL/SQL 检索 hibernate query language (面向对象的查询语言) * a) 不再操纵表,它操纵的是持久化类的对象 b) 面向对象的 3. QBC ( query by criteria ) 更加面向对象 4. QBE ( query by Example ) 5....

    hibernate

    Hibernate查询语言(Query Language), 即HQL 11.1. 大小写敏感性(Case Sensitivity) 11.2. from 子句 11.3. 联合(Associations)和连接(joins) 11.4. select子句 11.5. 统计函数(Aggregate ...

    Hibernate开发指南

    Hibernate Query Language (HQL).........................................36 数据关联 ........................................................................................................37 一对一...

    hibernate3.6 文档(pdf 格式)

    3.4.5. Query Language Substitution .................................................................. 43 3.4.6. Hibernate statistics ......................................................................

Global site tag (gtag.js) - Google Analytics