『转』Hibernate的子查询

对于支持子查询的数据库,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 cat.id, (select max(kit.weight) from cat.kitten kit) 
from Cat as cat

注意,HQL自查询只可以在select或者where子句中出现。

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

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

转载于:https://www.cnblogs.com/minideas/archive/2011/03/02/1968562.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值