百度空间 | 百度首页 
               
 
查看文章
 
HQL: Hibernate查询语言(2)
2007-05-31 16:51

15.8. 表达式

where子句中允许使用的表达式包括 大多数你可以在SQL使用的表达式种类:

  • 数学运算符+, -, *, /

  • 二进制比较运算符=, >=, <=, <>, !=, like

  • 逻辑运算符and, or, not

  • in, not in, between, is null, is not null, is empty, is not empty, member of and not member of

  • "简单的" case, case ... when ... then ... else ... end,和 "搜索" case, case when ... then ... else ... end

  • 字符串连接符...||... or concat(...,...)

  • current_date(), current_time(), current_timestamp()

  • second(...), minute(...), hour(...), day(...), month(...), year(...),

  • EJB-QL 3.0定义的任何函数或操作:substring(), trim(), lower(), upper(), length(), locate(), abs(), sqrt(), bit_length()

  • coalesce()nullif()

  • cast(... as ...), 其第二个参数是某Hibernate类型的名字,以及extract(... from ...),只要ANSI cast()extract() 被底层数据库支持

  • 任何数据库支持的SQL标量函数,比如sign(), trunc(), rtrim(), sin()

  • JDBC参数传入 ?

  • 命名参数:name, :start_date, :x1

  • SQL 直接常量 'foo', 69, '1970-01-01 10:00:01.0'

  • Java public static final 类型的常量 eg.Color.TABBY

关键字inbetween可按如下方法使用:

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' )

同样, 子句is nullis not null可以被用来测试空值(null).

在Hibernate配置文件中声明HQL“查询替代(query substitutions)”之后, 布尔表达式(Booleans)可以在其他表达式中轻松的使用:

<property name="hibernate.query.substitutions">true 1, false 0</property>

系统将该HQL转换为SQL语句时,该设置表明将用字符 10 来 取代关键字truefalse:

from Cat cat where cat.alive = true

你可以用特殊属性size, 或是特殊函数size()测试一个集合的大小。

from Cat cat where cat.kittens.size > 0
from Cat cat where size(cat.kittens) > 0

对于索引了(有序)的集合,你可以使用minindexmaxindex函数来引用到最小与最大的索引序数。 同理,你可以使用minelementmaxelement函数来 引用到一个基本数据类型的集合中最小与最大的元素。

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

在传递一个集合的索引集或者是元素集(elementsindices 函数) 或者传递一个子查询的结果的时候,可以使用SQL函数any, some, all, exists, in

select mother from Cat as mother, Cat as kit
where kit in elements(foo.kittens)
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)

注意,在Hibernate3种,这些结构变量- size, elements, indices, minindex, maxindex, minelement, maxelement - 只能在where子句中使用。

一个被索引过的(有序的)集合的元素(arrays, lists, maps)可以在其他索引中被引用(只能在where子句中):

from Order order where order.items[0].id = 1234
select person from Person person, Calendar calendar
where calendar.holidays['national day'] = person.birthDay
     and person.nationality.calendar = calendar
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

对于一个一对多的关联(one-to-many association)或是值的集合中的元素, HQL也提供内建的index()函数,

select item, index(item) from Order order 
     join order.items item
where index(item) < 5

如果底层数据库支持标量的SQL函数,它们也可以被使用

from DomesticCat cat where upper(cat.name) like 'FRI%'

如果你还不能对所有的这些深信不疑,想想下面的查询。如果使用SQL,语句长度会增长多少,可读性会下降多少:

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
     )

15.9. order by子句

查询返回的列表(list)可以按照一个返回的类或组件(components)中的任何属性(property)进行排序:

from DomesticCat cat
order by cat.name asc, cat.weight desc, cat.birthdate

可选的ascdesc关键字指明了按照升序或降序进行排序.

15.10. group by子句

一个返回聚集值(aggregate values)的查询可以按照一个返回的类或组件(components)中的任何属性(property)进行分组:

select cat.color, sum(cat.weight), count(cat) 
from Cat cat
group by cat.color
select foo.id, avg(name), max(name) 
from Foo foo join foo.names name
group by foo.id

having子句在这里也允许使用.

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)

如果底层的数据库支持的话(例如不能在MySQL中使用),SQL的一般函数与聚集函数也可以出现 在havingorder by 子句中。

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

注意group by子句与 order by子句中都不能包含算术表达式(arithmetic expressions).

15.11. 子查询

对于支持子查询的数据库,Hibernate支持在查询中使用子查询。一个子查询必须被圆括号包围起来(经常是SQL聚集函数的圆括号)。 甚至相互关联的子查询(引用到外部查询中的别名的子查询)也是允许的。

from Cat as fatcat 
where fatcat.weight > ( 
     select avg(cat.weight) from DomesticCat cat 
)
from DomesticCat as cat 
where cat.name = some ( 
     select name.nickName from Name as name 
)
from Cat as cat 
where not exists ( 
     from Cat as mate where mate.mate = cat 
)
from DomesticCat as cat 
where cat.name not in ( 
     select name.nickName from Name as name 
)

在select列表中包含一个表达式以上的子查询,你可以使用一个元组构造符(tuple constructors):

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

注意在某些数据库中(不包括Oracle与HSQL),你也可以在其他语境中使用元组构造符, 比如查询用户类型的组件与组合:

from Person where name = ('Gavin', 'A', 'King')

该查询等价于更复杂的:

from Person where name.first = 'Gavin' and name.initial = 'A' and name.last = 'King')

有两个很好的理由使你不应当作这样的事情:首先,它不完全适用于各个数据库平台;其次,查询现在依赖于映射文件中属性的顺序。

15.12. HQL示例

Hibernate查询可以非常的强大与复杂。实际上,Hibernate的一个主要卖点就是查询语句的威力。这里有一些例子,它们与我在最近的 一个项目中使用的查询非常相似。注意你能用到的大多数查询比这些要简单的多!

下面的查询对于某个特定的客户的所有未支付的账单,在给定给最小总价值的情况下,返回订单的id,条目的数量和总价值, 返回值按照总价值的结果进行排序。为了决定价格,查询使用了当前目录。作为转换结果的SQL查询,使用了ORDER, ORDER_LINE, PRODUCT, CATALOGPRICE 库表。

select order.id, sum(price.amount), count(item)
from Order as order
     join order.lineItems as item
     join item.product as product,
     Catalog as catalog
     join catalog.prices as price
where order.paid = false
     and order.customer = :customer
     and price.product = product
     and catalog.effectiveDate < sysdate
     and catalog.effectiveDate >= all (
         select cat.effectiveDate 
         from Catalog as cat
         where cat.effectiveDate < sysdate
     )
group by order
having sum(price.amount) > :minAmount
order by sum(price.amount) desc

这简直是一个怪物!实际上,在现实生活中,我并不热衷于子查询,所以我的查询语句看起来更像这个:

select order.id, sum(price.amount), count(item)
from Order as order
     join order.lineItems as item
     join item.product as product,
     Catalog as catalog
     join catalog.prices as price
where order.paid = false
     and order.customer = :customer
     and price.product = product
     and catalog = :currentCatalog
group by order
having sum(price.amount) > :minAmount
order by sum(price.amount) desc

下面一个查询计算每一种状态下的支付的数目,除去所有处于AWAITING_APPROVAL状态的支付,因为在该状态下 当前的用户作出了状态的最新改变。该查询被转换成含有两个内连接以及一个相关联的子选择的SQL查询,该查询使用了表 PAYMENT, PAYMENT_STATUS 以及 PAYMENT_STATUS_CHANGE

select count(payment), status.name 
from Payment as payment 
     join payment.currentStatus as status
     join payment.statusChanges as statusChange
where payment.status.name <> PaymentStatus.AWAITING_APPROVAL
     or (
         statusChange.timeStamp = ( 
             select max(change.timeStamp) 
             from PaymentStatusChange change 
             where change.payment = payment
         )
         and statusChange.user <> :currentUser
     )
group by status.name, status.sortOrder
order by status.sortOrder

如果我把statusChanges实例集映射为一个列表(list)而不是一个集合(set), 书写查询语句将更加简单.

select count(payment), status.name 
from Payment as payment
     join payment.currentStatus as status
where payment.status.name <> PaymentStatus.AWAITING_APPROVAL
     or payment.statusChanges[ maxIndex(payment.statusChanges) ].user <> :currentUser
group by status.name, status.sortOrder
order by status.sortOrder

下面一个查询使用了MS SQL Server的 isNull()函数用以返回当前用户所属组织的组织帐号及组织未支付的账。 它被转换成一个对表ACCOUNT, PAYMENT, PAYMENT_STATUS, ACCOUNT_TYPE, ORGANIZATION 以及 ORG_USER进行的三个内连接, 一个外连接和一个子选择的SQL查询。

select account, payment
from Account as account
     left outer join account.payments as payment
where :currentUser in elements(account.holder.users)
     and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID)
order by account.type.sortOrder, account.accountNumber, payment.dueDate

对于一些数据库,我们需要弃用(相关的)子选择。

select account, payment
from Account as account
     join account.holder.users as user
     left outer join account.payments as payment
where :currentUser = user
     and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID)
order by account.type.sortOrder, account.accountNumber, payment.dueDate

15.13. 批量的UPDATE & DELETE语句

HQL现在支持UPDATE与DELETE语句. 查阅 第 14.3 节 “大批量更新/删除(Bulk update/delete)” 以获得更多信息。

15.14. 小技巧 & 小窍门

你可以统计查询结果的数目而不必实际的返回他们:

( (Integer) session.iterate("select count(*) from ....").next() ).intValue()

若想根据一个集合的大小来进行排序,可以使用如下的语句:

select usr.id, usr.name
from User as usr 
     left join usr.messages as msg
group by usr.id, usr.name
order by count(msg)

如果你的数据库支持子选择,你可以在你的查询的where子句中为选择的大小(selection size)指定一个条件:

from User usr where size(usr.messages) >= 1

如果你的数据库不支持子选择语句,使用下面的查询:

select usr.id, usr.name
from User usr.name
     join usr.messages msg
group by usr.id, usr.name
having count(msg) >= 1

因为内连接(inner join)的原因,这个解决方案不能返回含有零个信息的User 类的实例, 所以这种情况下使用下面的格式将是有帮助的:

select usr.id, usr.name
from User as usr
     left join usr.messages as msg
group by usr.id, usr.name
having count(msg) = 0

JavaBean的属性可以被绑定到一个命名查询(named query)的参数上:

Query q = s.createQuery("from foo Foo as foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean包含方法getName()与getSize()
List foos = q.list();

通过将接口Query与一个过滤器(filter)一起使用,集合(Collections)是可以分页的:

Query q = s.createFilter( collection, "" ); // 一个简单的过滤器
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();

通过使用查询过滤器(query filter)可以将集合(Collection)的原素分组或排序:

Collection orderedCollection = s.filter( collection, "order by this.amount" );
Collection counts = s.filter( collection, "select this.type, count(this) group by this.type" );

不用通过初始化,你就可以知道一个集合(Collection)的大小:

( (Integer) session.iterate("select count(*) from ....").next() ).intValue();

类别:Hibernate | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu